Login with superuser not working in django admin panel
I was writing code, everything worked fine, all services were running via docker-compose, then the database crashed, I had to clean up the database files and recreate them using the same docker-compose. This time, I tried to create an admin user using python manage.py createsuperuser, I created it, but I can't authenticate with it in django/admin.
Settings:
from pathlib import Path
import environ
import os
env = environ.Env(DEBUG=(bool, False))
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env('DEBUG')
ALLOWED_HOSTS = []
INTERNAL_IPS = [
"127.0.0.1",
]
AUTH_USER_MODEL = 'codenest.User'
TAILWIND_APP_NAME = 'theme'
# AUTHENTICATION_BACKENDS = [
# 'django.contrib.auth.backends.RemoteUserBackend',
# 'django.contrib.auth.backends.ModelBackend',
# ]
SITE_ID = 1
INSTALLED_APPS = [
'codenest.apps.CodenestConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tailwind',
'theme',
'django_browser_reload',
]
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.auth.middleware.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django_browser_reload.middleware.BrowserReloadMiddleware',
]
ROOT_URLCONF = 'learning_system.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'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 = 'learning_system.wsgi.application'
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
DATABASES = {
'default': {
"ENGINE": "django.db.backends.postgresql_psycopg2",
"NAME": env("SQL_NAME"),
"USER": env("SQL_USER"),
"PASSWORD": env("SQL_PASSWORD"),
"HOST": env("HOST"),
"PORT": env("PORT"),
}
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://redis:6379/0",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/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/5.0/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/5.0/howto/static-files/
STATIC_URL = 'codenest/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# EMAIL_BACKEND="django.core.main.backends.smtp.EmailBackend"
EMAIL_HOST=env('EMAIL_HOST')
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=env('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD=env('EMAIL_HOST_PASSWORD')
Models:
import os
import shutil
from django.utils import timezone
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, AbstractUser
from django.dispatch import receiver
from django.db.models.signals import post_delete
# Create your models here.
def course_image_path(instance, filename):
ext = filename.split('.')[-1]
new_filename = f"{instance.name.replace(' ', '_')}/{instance.name.replace(' ', '_')}.{ext}"
return os.path.join('course_images', new_filename)
class User(AbstractUser):
email = models.EmailField(unique=True)
username = models.CharField(max_length=120, unique=True)
is_active = models.BooleanField(default=False)
def __str__(self) -> str:
return f"name: {self.username} is_staff: {self.is_staff}" \
f" is_superuser: {self.is_superuser} is_actvie: {self.is_active}"
class Course(models.Model):
name = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=1000, default='Empty')
author = models.CharField(max_length=100, default='Empty')
image = models.ImageField(upload_to=course_image_path, unique=True, default='trashhold.png', )
price = models.DecimalField(decimal_places=2, max_digits=5)
is_active = models.BooleanField()
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
# This is the signal that is triggered then we remove the course
@receiver(post_delete, sender=Course)
def auto_delete_file_course(sender, instance, **kwargs):
if instance.image:
if os.path.isfile(instance.image.path):
os.remove(instance.image.path) # For remove image
folder_path = os.path.dirname(instance.image.path)
shutil.rmtree(folder_path) # For remove directory
Most likely your superuser status is_active=False, so you cannot log into the admin panel.
Therefore, first of all, check the is_active flag. You didn't have to add this field to your model, because this logic matches Django's logic.