在创建超级用户时出现Django属性错误。

14 浏览
0 Comments

在创建超级用户时出现Django属性错误。

我使用AbstractBaseUser创建了一个自定义的用户模型。当我尝试通过终端使用createsuperuser命令创建超级用户时,出现了以下错误:

在create_superuser中
用户.is_staff = True
AttributeError: 无法设置属性

以下是我创建自定义用户模型的代码。

import uuid
from django.db import models
from django.contrib.auth.models import (
 AbstractBaseUser, AbstractUser, BaseUserManager
)
class AdminUserManager(BaseUserManager):
 def create_user(self, email_id, password=None, *args, **kwargs):
  if not email_id:
   raise ValueError('用户必须有一个电子邮件ID')
  user = self.model(email_id=email_id)
  user.set_password(password)
  user.save(using = self._db)
  return user
 def create_staffuser(self, email_id, password, *args, **kwargs):
  user = self.create_user(
   email_id, password=password
  )
  user.is_staff = True
  user.save(using = self._db)
  return user
 def create_superuser(self, email_id, password, *args, **kwargs):
  user = self.create_user(
   email_id, password=password
  )
  user.is_staff = True
  user.is_superuser = True
  user.save(using = self._db)
  return user
USER_ROLE = (
  ('pilot', '飞行员'),
  ('admin', '管理员')
)
class AdminUser(AbstractBaseUser):
  user_uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  profile_picture = models.ImageField(upload_to='user_profile_picture/', null=True, blank=True)
  user_role = models.CharField(max_length=10, choices=USER_ROLE)
  email_id = models.EmailField(verbose_name='电子邮件ID', unique=True)
  first_name = models.CharField(max_length=100)
  last_name = models.CharField(max_length=100)
  phone_number = models.CharField(max_length=20)
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)
  is_verified = 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_id'
  REQUIRED_FIELDS = ['first_name', 'last_name']
  def get_full_name(self):
   full_name = f'{self.first_name} {self.last_name}'
   return full_name
  def get_short_name(self):
   return self.first_name
  def __str__(self):
   return self.email_id
  @property
  def is_staff(self):
   return self.is_staff
  @property
  def is_superuser(self):
   return self.is_superuser
  objects = AdminUserManager()

0