I want my Django project to authenticate users with their email instead of their user-name. I followed this suggestion, but it doesn't work.
This is my EmailBackend
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class EmailBackend(ModelBackend):
def authenticate(self, username=None, password=None, **kwars):
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
except UserModel.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None
I have added AUTHENTICATION_BACKENDS = ['GeneralApp.utils.EmailBackend']
to settings.py and, when it is commented, I can login using user-name, and when I uncomment it, I cannot login anymore. I have traced out that the code of GeneralApp.utils.EmailBackend.authenticate()
is never executed, but I know Django can locate the class because I have misspelled it intentionally and I get an error, and when I correct the typo, no exception is raised. I also know that the default authentication backend was effectively override because I cannot neither login with user-name. I have this same solution working perfectly in another project so I cannot understand why the custom authentication code is never executed when the class is perfectly located with AUTHENTICATION_BACKENDS
set to it.