无法登录到管理员:自定义用户模型

时间:2019-01-10 00:49:47

标签: django

我可以使用命令行进行身份验证

>>> from django.contrib.auth import authenticate
>>> user = authenticate(username='shiva@gmail.com',password='123456')
>>> user
<Employee: shiva@gmail.com>
>>> 

但是我无法使用以下网址登录: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']

1 个答案:

答案 0 :(得分:0)

我认为该用户不是您要使用用户名和密码登录到adminsite的superuserstaff用户。尝试使用python manage.py createsuperuser创建一个新用户,然后使用该用户登录adminsite。您还可以从shell(shiva@gmail.com)向用户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()

然后使用该用户登录到管理员站点。