Hey guys I tried my best but I am not able to log in to the django admin panel with my custom user model. I did do all the things I can, I also did the authentication for the email and the rest but I still am not able to log into the django admin panel it keeps saying this:
Please enter the correct email and password for a staff account. Note that both fields may be case-sensitive.
I tried and checked my password probably a hundred times now but still I won't let me log in.
Can someone please help me with this, it would be the biggest help ever. I have been stuck here for like a month now.
I have pasted all the code that I did below.
models.py:
from django.db import models
import uuid
from django.utils import timezone
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager
from django.utils.translation import gettext_lazy as _
class CustomAccountManager(BaseUserManager):
def create_user(self, first_name, last_name, phone_number, email, password, **other_fields):
if not email:
raise ValueError(_('You must provie an email address'))
if not first_name:
raise ValueError(_('You must provide a first name'))
if not last_name:
raise ValueError(_('You must provide a last name'))
email = self.normalize_email(email)
user = self.model(email=email, first_name=first_name, last_name=last_name, phone_number=phone_number, **other_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, first_name, last_name, phone_number, password, **other_fields):
other_fields.setdefault('is_staff', True)
other_fields.setdefault('is_superuser', True)
other_fields.setdefault('is_active', True)
if other_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must be assigned to is_staff=True'))
if other_fields.get('is_active') is not True:
raise ValueError(_('Superuser must be assigned to is_active=True'))
if other_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must be assigned to is_superuser=True'))
return self.create_user(email, first_name, last_name, password, phone_number, **other_fields)
class NewUser(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=200, null=True, blank=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
email = models.EmailField(max_length=200, null=True, blank=True, unique=True)
password = models.CharField(max_length=200,null=True, blank=True)
confirm_password = models.CharField(max_length=200, null=True, blank=True)
phone_number = models.CharField(max_length=10,null=True, blank=True)
address = models.TextField(null=True, blank=True)
pin_code = models.CharField(null=True, max_length=6, blank=True)
region = models.CharField(null=True, max_length=200, blank=True)
state = models.CharField(null=True, max_length=100, blank=True)
start_date = models.DateField(default=timezone.now)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
objects = CustomAccountManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'phone_number']
def __str__(self):
return self.first_name + ' ' + self.last_name
Authentication.py:
from .models import NewUser
from django.contrib.auth.backends import BaseBackend
class EmailAuthBackend(BaseBackend):
model = NewUser
def authenticate(self, request = None, email=None, password=None):
try:
user = self.model.objects.get(email=email)
except self.model.DoesNotExist:
return None
if self.model.check_password(password) and user is not None:
return user
def get_user(self, user_id):
try:
return self.model.objects.get(id=user_id)
except self.model.DoesNotExist:
return None
admin.py:
from django.contrib import admin
from .models import NewUser
# Register your models here.
admin.site.register(NewUser)
settings.py:
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user.apps.UserConfig',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'LavanderWoods.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'LavanderWoods.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
AUTH_USER_MODEL = 'user.NewUser'
AUTHENTICATION_BACKENDS = [
'user.authentication.EmailAuthBackend',
'django.contrib.auth.backends.ModelBackend',
]
Thats all the code that is needed for this custom user model. Someone please help I am fed up of this, like really really fed up.
Simply you can try this:
In models.py:
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
)
class UserManager(BaseUserManager):
'''Manager for users.'''
def create_user(self, email, password=None, **extra_fields):
'''Create, save and return a new user.'''
if not email:
raise ValueError('User must have an email address.')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
'''Create and return a new superuser.'''
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser, PermissionsMixin):
'''User in the system.'''
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
Note: This is email based login.