I am working on a django authentication project, where I want to authenticate using both email and username for authentication. The model is
class LinksUser(AbstractBaseUser, PermissionsMixin):
objects = LinksUserManager()
full_name = models.CharField(max_length=200, blank=False)
email = models.EmailField(_("email address"), unique=True)
username = models.CharField(_("username"), unique=True, max_length=20)
is_active = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = "username"
EMAIL_FIELD = "email"
REQUIRED_FIELDS = ['email']
def __str__(self):
return self.email
In addition I have created a manager file which is
class LinksUserManager(BaseUserManager):
"""
Custom user-model manager where the email and username are identifiers
for authentication
"""
def create_user(self, email, username, password, **extra_fields):
if not username:
raise ValueError('Username must be set')
if not email:
raise ValueError('Email must be set')
email = self.normalize_email(email)
user = self.model(username=username, email=email)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(username, email, password, **extra_fields)```
Finally, I wrote an authentication code of
from .models import LinksUser
class LinkUserBackend(object): """ Model backend that attempts to allow a user to log in with either the username or the email address """
def authenticate(self, request, username=None, password=None):
try:
user = LinksUser.objects.get(email=username)
except LinksUser.DoesNotExist:
try:
user = LinksUser.objects.get(username=username)
except LinksUser.DoesNotExist:
return None
if user.check_password(password):
return user
can anyone please tell me why my authentication procress may not be allowing me to login eventhough creating the superuser ask for everything that I told it to.