Email login using Django
Aug 31, 2010
Dick Brouwer
1 minute read

There are plenty of sites that explain you how to enable email-based authentication in Django vs. the default username auth. However, one thing that is often forgotten: emails should be treated case-insensitive. Here is a (trivial) custom authentication backend that allows case-insensitive logins.

Furthermore, don’t forget to override the clean_username method of the UserCreationForm class to check if a ‘case-insensitive’ username exist. I’ve added some other goodies as well that force email validation on the username field, add a ‘confirm to the terms’ and conditions checkbox, and set the email address in the User object.

class EmailUserCreationForm(UserCreationForm):
    '''
    User login form class that replaces the 'username' field with
    an 'emailfield' on registration, sets email = username in the
    User object, and adds case-insensitive username verification.
    '''
    username = forms.EmailField(label=("Email Address"))
    confirm = forms.BooleanField(error_messages={'required':
                'Please read and accept the Terms and Conditions to continue'})

    def clean_username(self):
        username = self.cleaned_data["username"]
        try:
            User.objects.get(username__iexact=username)
        except User.DoesNotExist:
            return username
        raise forms.ValidationError(_("A user with that username already exists."))


    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.email = user.username
            user.save()
        return user


comments powered by Disqus