Authored by Aaron Arredondo Sanchez

login with email or username - Django

from django.conf import settings
from django.contrib.auth import get_user_model

class EmailOrUsernameModelBackend(object):
    This is a ModelBacked that allows authentication with either a username or an email address.

    def authenticate(self, username=None, password=None):
        if '@' in username:
            kwargs = {'email': username}
            kwargs = {'username': username}
            user = get_user_model().objects.get(**kwargs)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

    def get_user(self, username):
            return get_user_model().objects.get(pk=username)
        except get_user_model().DoesNotExist:
            return None
21 Bytes
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment