Skip to content Skip to sidebar Skip to footer

Django Authentication With Custom User Model With Email-id As Unique Key

to achieve unique constraint (without repetition of default user models fields) on email-id I did this from django.contrib.auth.models import AbstractUser class User(AbstractUser):

Solution 1:

You need to define backends.py like this:

from django.contrib.auth.models import User, check_password

class EmailAuthBackend(object):
"""
Email Authentication Backend

Allows a user to sign in using an email/password pair rather than
a username/password pair.
"""

def authenticate(self, username=None, password=None):
    """ Authenticate a user based on email address as the user name. """
    try:
        user = User.objects.get(email=username)
        if user.check_password(password):
            return user
    except User.DoesNotExist:
        return None 

def get_user(self, user_id):
    """ Get a User object from the user_id. """
    try:
        return User.objects.get(pk=user_id)
    except User.DoesNotExist:
        return None

And in your settings file add this:

AUTHENTICATION_BACKENDS = ('backends.EmailAuthBackend',)

This will enable the login with email.

For more details visit this.


Post a Comment for "Django Authentication With Custom User Model With Email-id As Unique Key"