django - 无法登录管理员:自定义用户模型
问题描述
我可以使用命令行进行身份验证
>>> from django.contrib.auth import authenticate
>>> user = authenticate(username='shiva@gmail.com',password='123456')
>>> user
<Employee: shiva@gmail.com>
>>>
但我无法使用 url 登录:http://localhost:8000/admin/login/?next=/admin/
显示以下错误:
请为员工帐户输入正确的电子邮件地址和密码。两个地方都要注意大小写。
模型
from django.db import models
from django.contrib.auth.models import (BaseUserManager,AbstractBaseUser, PermissionsMixin)
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
date_of_birth=date_of_birth,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Employee(AbstractBaseUser,PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField(default=None)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
objects = MyUserManager()
REQUIRED_FIELDS = ['date_of_birth']
解决方案
我认为该用户不是您superuser
使用staff
用户名和密码登录到管理站点的用户。尝试使用创建一个新用户python manage.py createsuperuser
,并使用它登录到管理站点。您还可以shiva@gmail.com
从 shell( python manage.py shell
) 为用户分配管理员状态。像这样:
from <your_app>.models import Employee
shiva = Employee.objects.get(email='shiva@gmail.com')
shiva.is_superuser = True
shiva.is_staff = True
shiva.save()
然后使用此用户登录到 adminsite。
推荐阅读
- java - 对 hashmap 进行排序并按顺序获取一个键(第二个键、第三个等)
- vb.net - system.windows.forms.notifyicon 不工作 vb.net
- html - HTML 正文内容阻塞了导航
- sql - 我无法在 SQLite 中按日期过滤
- regex - 正则表达式检查多个字符的确切出现次数
- arrays - 在 JSON 中的对象中创建对象中的对象
- python - 在 Python 中从数据库中调用类和函数名
- kotlin - 如何在 Kotlin 中添加人员列表?
- python - 从 netcat 获取输出并发送响应
- python - 如何将字符串转换为枚举列表