Django Authentication With Email Instead of Usernames
Posted: March 15th, 2010 | Author: Arif Harbott | Filed under: Django | Tags: auth backends, email, email auth, usernames | No Comments »A lot of the applications we build use email addresses instead of usernames. Personally I find it a lot easier to remember my email address than an ever growing list of usernames.
The way we do this is to write a simple custom auth backend in the following way:
1. In settings.py add the following lines (replace yourprojectname with the name of your app):
AUTHENTICATION_BACKENDS = (
'yourprojectname.backends.EmailAuthBackEnd',
'django.contrib.auth.backends.ModelBackend',
)
2. Create a file called backends.py and put it in your root folder (i.e. the same folder as settings.py)
from django.contrib.auth.backends import ModelBackend
from django.contrib.admin.models import User
class EmailAuthBackEnd(ModelBackend):
def authenticate(self, email=None, password=None,**kwargs):
try:
user = User.objects.get(email=email)
if user.check_password(password):
return user
return None
except User.DoesNotExist:
return None
3. In your views import the authenticate back end and then call the authenticate function:
from django.contrib.auth import authenticate .... user = authenticate(email=email, password=password)

Leave a Reply