Django-Registration: Email as username

Eva611 picture Eva611 · Jun 15, 2011 · Viewed 14.4k times · Source

How do I use emails instead of username for authentication using django-registration.

Further how do I enforce this change once I have already installed the registration module.

Do I edit the solution here Anyone knows a good hack to make django-registration use emails as usernames? in the lib folder?

Answer

Matt picture Matt · Jun 17, 2011

Dear fellow Django Coder,

I think this is the best way to do it. Good luck!

First step, is to create the form you'd like to use.

project/accounts/forms.py

from django import forms
from registration.forms import RegistrationForm
from django.contrib.auth.models import User

class Email(forms.EmailField): 
    def clean(self, value):
        super(Email, self).clean(value)
        try:
            User.objects.get(email=value)
            raise forms.ValidationError("This email is already registered. Use the 'forgot password' link on the login page")
        except User.DoesNotExist:
            return value


class UserRegistrationForm(forms.Form):
    password1 = forms.CharField(widget=forms.PasswordInput(), label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput(), label="Repeat your password")
    #email will be become username
    email = Email()

    def clean_password(self):
        if self.data['password1'] != self.data['password2']:
            raise forms.ValidationError('Passwords are not the same')
        return self.data['password1']

Here you are creating a file to override the register() function in django-registration.

project/accounts/regbackend.py

from django.conf import settings
from django.contrib.sites.models import RequestSite
from django.contrib.sites.models import Site

from registration import signals
from registration.forms import RegistrationForm
from registration.models import RegistrationProfile

from registration.backends import default


class Backend(default.DefaultBackend):
    def register(self, request, **kwargs):
        email, password = kwargs['email'], kwargs['password1']
        username = email
        if Site._meta.installed:
            site = Site.objects.get_current()
        else:
            site = RequestSite(request)
        new_user = RegistrationProfile.objects.create_inactive_user(username, email,
                                                                    password, site)
        signals.user_registered.send(sender=self.__class__,
                                     user=new_user,
                                     request=request)
        return new_user

Direct your urls to paths you want to use.

project/urls.py

(r'^accounts/', include('registration.backends.default.urls')),

Tell your urls to use the custom backend for the registration view. Also, import the form you created and add it to the url to be processed by the view.

project/accounts/urls.py

from django.conf.urls.defaults import *
from registration.backends.default.urls import *
from accounts.forms import UserRegistrationForm

urlpatterns += patterns('',

    #customize user registration form
    url(r'^register/$', 'registration.views.register',
        {
            'backend': 'accounts.regbackend.Backend',
            'form_class' : UserRegistrationForm
        },
        name='registration_register'
    ),

) 

Hope that works!

-Matt