By default, Django stores both a username and email field for each user. According to the docs, the
authenticate() function in
django.contrib.auth expects the user to login with a username, not an email address.
But what if someone accidentally tries to login using their email address. That should still get them logged in, right?
from django.contrib import auth from django.contrib.auth.models import User ... user = auth.authenticate(username=username, password=pwd) if not user: try: u = User.objects.get(email=username) user = auth.authenticate(username=u.username, password=pwd) except User.DoesNotExist: pass if user is not None and user.is_active: auth.login(request, user)
If we're unable to authenticate them using the "username" they provide, try looking up a User with that as their email address, and then use that User's username to authenticate.