使用自定义用户模型成功创建超级用户后无法登录到 django admin

Can't login to django admin after successfully creating a super user with a custom user model

imm 尝试使用成功创建的超级用户登录到 django 管理面板,但无法获得正确的 username/pw 组合。

我希望用户只使用他们的电子邮件作为用户名。我已经删除了 migrations、sycndb,除了登录管理面板外一切正常。

models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager


class MyAccountManager(BaseUserManager):
    def create_user(self, email, username, password= None):
        if not email:
            raise ValueError('email required')
        if not username:
            raise ValueError('username required')

        user = self.model(
            email= self.normalize_email(email),
            username= username,
        )
        user.set_password(password)
        user.save(using= self._db)
        return user

    def create_superuser(self, email, username, password):
        user = self.create_user(
            email= self.normalize_email(email),
            password= password,
            username= username,
        )
        user.is_admin= True
        user.staff= True
        user.is_superuser= True
        user.save(using= self._db)
        return user


class Accounts(AbstractBaseUser):
    email                   = models.EmailField(verbose_name= 'email', max_length= 60, unique= True)
    username                = models.CharField(max_length= 30, unique= True)
    date_joined             = models.DateTimeField(verbose_name= 'date joined', auto_now_add= True)
    last_login              = models.DateTimeField(verbose_name= 'last login', auto_now= True)
    is_admin                = models.BooleanField(default= False)
    is_active               = models.BooleanField(default= True)
    is_staff                = models.BooleanField(default= False)
    is_superuser            = models.BooleanField(default= False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = MyAccountManager()

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj= None):
        return self.is_admin

    def has_module_perm(self, app_label):
        return True


admin.py

from django.contrib import admin
from .models import Accounts

admin.site.register(Accounts)

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'articles',
    'accounts',
]

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',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}

AUTH_USER_MODEL = 'accounts.Accounts'


ROOT_URLCONF = 'restApi.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',
            ],
        },
    },
]

我认为这一定与密码的保存和返回方式有关,因为无论我做什么,我都会收到“请输入员工帐户的正确电子邮件和密码。请注意,这两个字段可能区分大小写。”留言。

imm 使用 mongodb 数据库。

您在 MyAccountManager.create_superuser() 中设置 user.staff= True,但它应该是 user.is_staff = True(您缺少 is_ ).

您会在这里找到可能对您有帮助的答案:

如果您仍然无法登录,运行 python manage.py createsuperuser 并创建一个新的超级用户并尝试使用该超级用户登录