You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Admin面板超级用户登录失败问题求助

Django后台超级用户无法登录排查方案

问题背景

之前通过docker-compose运行所有服务正常,数据库崩溃后清理了数据库文件,用同一个docker-compose重建数据库。执行python manage.py createsuperuser创建超级用户后,无法在django/admin页面完成身份验证。

项目配置

Settings.py

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.py

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 

排查与解决步骤

  • 激活用户状态
    你自定义的User模型中is_active默认是False,但创建超级用户时这个字段不会自动设为True,而Django后台登录要求用户必须处于活跃状态。解决方法:

    • 打开Django shell:python manage.py shell
    • 执行代码激活用户:
      from codenest.models import User
      user = User.objects.get(username="你的超级用户名")
      user.is_active = True
      user.save()
      

    修改完成后重新尝试登录后台。

  • 调整中间件配置
    当前中间件列表里RemoteUserMiddleware放在AuthenticationMiddleware之后,虽然你注释了对应的认证后端,但这个中间件可能干扰默认的账号密码认证流程。如果激活用户后仍无法登录,可以暂时注释掉RemoteUserMiddleware,重启服务后再测试。

  • 验证数据库数据正确性

    • 确认docker-compose启动的PostgreSQL服务正常,Django能正常连接数据库。
    • 检查创建超级用户时是否有报错,确认用户数据已写入数据库。可以在Django shell中查询用户的is_superuser和is_staff字段是否为True,这两个字段是后台登录的必要条件。
  • 清除缓存
    项目使用Redis作为缓存,可能残留旧的会话数据导致认证异常。可以重启Redis容器,或者在Django shell中执行以下代码清除缓存:

    from django.core.cache import cache
    cache.clear()
    

    同时清空浏览器的Cookie和缓存,再尝试登录。


内容的提问来源于stack exchange,提问作者KraNf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:04:58