我需要创建自定义用户模型,因为我需要再添加一个称为角色的字段。如果提供了角色,则应将其分配给用户模型,否则在用户模型中提供代理作为角色。我继承了AbstractUser
。这样,在创建用户时,首先将密码另存为纯文本,另一种是用户无法登录,即表示无法登录。因此,我尝试了以下方法,如docs中所示,但问题是我不需要电子邮件部分,因此我将其排除在外,只使用了用户名和密码,但出现了类似TypeError: create_superuser() got an unexpected keyword argument 'email'
class UserManager(BaseUserManager):
def create_user(self, username, password=None):
"""
Creates and saves a User with the given username, date of
birth and password.
"""
if not username:
raise ValueError('Users must have an username')
user = self.model(username=username)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, password):
"""
Creates and saves a superuser with the given username and password.
"""
user = self.create_user(
username=username,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class Role(models.Model):
ROLE_CHOICES = (
('agent', 'Agent'),
('agency', 'Agency'),
('manufacturer', 'Manufacturer'),
)
role = models.CharField(max_length=15, choices=ROLE_CHOICES)
def __str__(self):
return self.role
class User(AbstractUser):
role = models.ForeignKey(
Role,
on_delete=models.CASCADE,
blank=True,
null=True,
)
objects = UserManager()
def __str__(self):
return self.username
@receiver(models.signals.post_save, sender=User)
def add_role_to_user(sender, instance, **kwargs):
print('instance in add role', instance)
if kwargs.get('created'):
try:
role = Role.objects.get(user=instance)
print('role', role)
except Role.DoesNotExist:
Role.objects.create(role="agent")
try:
token = Token.objects.get(user=instance)
print('token', token)
except Token.DoesNotExist:
Token.objects.create(user=instance)
答案 0 :(得分:3)
由于您在 create_superuser()
中不使用电子邮件,因此可以将电子邮件作为关键参数添加,并设置为None
作为
def create_superuser(self, username, password, email=None):
"""
Creates and saves a superuser with the given username and password.
"""
user = self.create_user(
username=username,
password=password,
)
user.is_superuser = True
user.save(using=self._db)
return user