Use email addresses for user name for django 1.0+

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""
@author: chris
"""
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.forms.fields import email_re

class EmailBackend(ModelBackend):
    """
    Authenticates against django.contrib.auth.models.User.
    """
    def authenticate(self, username=None, password=None):
        #If username is an email address, then try to pull it up
        if email_re.search(username):
            try:
                user = User.objects.get(email=username)
            except User.DoesNotExist:
                return None
        else:
            #We have a non-email address username we should try username
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                return None
        if user.check_password(password):
            return user

        

More like this

  1. Use email addresses for user name by chris 6 years, 2 months ago
  2. Use email addresses for user name for django 1.3 by kidzik 1 year, 11 months ago
  3. Login with email or username by zeeg 4 years, 9 months ago
  4. Authenticate with Email Address by thom 6 years, 1 month ago
  5. Django Registration without username by newmaniese 5 years, 1 month ago

Comments

revolunet (on December 30, 2009):

thanx, very nice example

#

styts (on January 6, 2010):

thanks, i had a hard time figuring out the correct solution due to all the comments in the /snippets/74/ thread.

#

jokull (on January 8, 2010):

Check out: http://bitbucket.org/jokull/django-email-login/

Also includes a simple django-registration backend and forms. Requires a recent checkout of Django.

#

joncombe (on February 13, 2011):

Nice solution, thank you.

I did find a tiny edge-case problem with users who registered on my site, unregistered themselves, then re-registered again because this caused the User.objects.get() line to return > 1 result. To fix it, simply change, user = User.objects.get(email=username) to user = User.objects.get(email=username, is_active=True) on lines 16 and 22.

#

kidzik (on June 13, 2011):

I've posted updated version for django 1.3

#

(Forgotten your password?)