Pages

0 comments

Django login with email or username

My new django project requires users to log in using their username or email. I googled and searched SO for a solution. But most of them were for authentication using email or creating a new backend. I wanted to allow my users to log in using email or username and I am too lazy to write a new authentication backend.  So I extended default django authentication form . And with the help of this snippet I came up with this solution. And obviously emails for users are made unique.

forms.py
from django.utils.translation import ugettext, ugettext_lazy as _
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import authenticate
        
class MyAuthenticationForm(AuthenticationForm):
    username = forms.CharField(label=_("Username"), max_length=100)
    #max length changed from 30 to 100
    def clean(self):
        username = self.cleaned_data.get('username').lower()
        password = self.cleaned_data.get('password')

        if username and password:
            #modifying clean method
            #next 5 lines are added
            if '@' in username:#checking if email
                try:
                    #getting username from the User object for that email
                    username = User.objects.get(email=username).username
                except:
                    User.DoesNotExist
            self.user_cache = authenticate(username=username,
                                           password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'])
            elif not self.user_cache.is_active:
                raise forms.ValidationError(self.error_messages['inactive'])
        self.check_for_test_cookie()
        return self.cleaned_data
urls.py
url(r'^login/$', 'django.contrib.auth.views.login',
            {'authentication_form':MyAuthenticationForm }),

Happy coding.:)