I have a form that only allow users to login via username . I decided to only allow user to login via email instead of username.
First, this is not a duplication of any
You can also write a custom backend:
# yourapp.backends.py
from django.contrib.auth.models import User
class EmailOrUsernameModelBackend(object):
""" Authenticate user by username or email """
def authenticate(self, username=None, password=None):
if '@' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = User.objects.get(**kwargs)
if user.check_password(password):
return user
else:
return None
except User.DoesNotExist:
return None
def get_user(self, user_id=None):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Now add your backend to settings.py:
AUTHENTICATION_BACKENDS = (
'yourapp.backends.EmailOrUsernameModelBackend',
'django.contrib.auth.backends.ModelBackend',
)