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"]
        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)
        if commit:
   = user.username
        return user

comments powered by Disqus