user1544500 user1544500 - 7 months ago 66
Python Question

Django-registration how to check if user exists

I'm using Django-registration with Django 1.8.15 to register users. My
looks like this:

from registration.backends.hmac.views import RegistrationView

url(r'^registration/register/$', RegistrationView.as_view(form_class=MyCustomSubscriberForm), name="registration_register"),

This is basically a CBV where I provide the form and the template.
Here's the form:

class MyCustomSubscriberForm(RegistrationForm):

class Meta:
model = MyCustomSubscriber
fields = ('firstname', 'surname', 'email', )

My problem is how to handle validation in this CBV?

At the moment if e.g. somebody tries to register with an already used email address Django gives a
IntegrityError at /registration/register/

What is the best way to use Validators from Django-registrations? For instance - how do I make sure that if a user with a certain e-mail already exists the users gets notified in the template?

How to extend this CBV or handle this error in my code with those validators already provided by Django-Registration?


After looking into Django-registration more carefully I discovered that Django-registration already has this functionality implemented in one of its forms: RegistrationFormUniqueEmail which is a subclass of RegistrationForm.

To make use of it I just had to subclass it in my form like this:

class MyCustomSubscriberForm(RegistrationFormUniqueEmail):

    def __init__(self, *args, **kwargs):
        super (RegistrationFormUniqueEmail, self).__init__(*args, **kwargs)

   class Meta: 
      model = get_user_model()
      fields = ('firstname', 'lastname', 'email') 

And that was it - the form was checking the if the provided email address is unique.