I opted to customize a little.
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
class EmailBackend(ModelBackend):
"""A django.contrib.auth backend that authenticates the user based on its
email address instead of the username.
"""
def authenticate(self, email=None, password=None):
"""Authenticate user using its email address instead of username."""
try:
user = User.objects.get(email=email)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
Then setup settings accordingly (notice that I wrote the backend inside an app called 'accounts'):
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend', # necessary for django.auth
'accounts.backends.EmailBackend' # custom backend to authenticate using the email field
)
And then modify your login view:
if request.method == 'POST' and username and password:
user = auth.authenticate(username=username, password=password)
if user is None:
user = auth.authenticate(email=email, password=password)
What do you think? I know it is not that simple but I couldn't figure out an easier/cleaner way to do it.