这个问题通常发生在使用Django自带的User模型扩展中,用户自定义模型的元数据可能未正确声明继承自AbstractBaseUser和PermissionsMixin。应该在扩展User模型时使用如下代码:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class MyUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The Email field must be set')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, password, **extra_fields)
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
date_joined = models.DateTimeField(auto_now_add=True)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def get_full_name(self):
return f"{self.first_name} {self.last_name}"
def get_short_name(self):
return self.first_name
这样定义用户模型可实现用户的登录和认证等系统功能。具体的model可以根据实际情况进行更改。