我有一个自定义用户模型如下。当我尝试创建一个超级用户时,它会问我组织(organization_id),我不想给予超级用户(因为只有当用户给组织时才有意义,因为我需要创建一个超级用户只是为了查看数据库,而且超级用户不属于任何组织)。我该怎么做来纠正这个问题。
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
# Create your models here.
class Organisation(models.Model):
organisation_name = models.CharField(max_length = 256)
contact_no = models.IntegerField()
email = models.EmailField()
class Meta():
unique_together = ['organisation_name','email']
def __str__(self):
return self.organisation_name
class MyUserManager(BaseUserManager):
def create_user(self, username, organisation, email, password):
email = self.normalize_email(email)
user = self.model(username=username, email=email, organisation=organisation)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, username, email, password, organisation):
user = self.create_user(username=username, email=email, password=password,organisation=organisation)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class MyUser(AbstractBaseUser):
username = models.CharField(max_length=256,unique=True)
email = models.EmailField(max_length=256)
organisation = models.ForeignKey(Organisation,on_delete=models.CASCADE,null=True)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ['email','organisation']
objects = MyUserManager()
def __str__(self):
return self.username
views.py
class Create_Accounts(CreateView):
model = models.MyUser
fields=('__all__')
template_name = 'accounts/create_account.html'
success_url = reverse_lazy("accounts:inner_index")
settings.py
AUTH_USER_MODEL = 'accounts.MyUser'
1条答案
按热度按时间ttp71kqs1#
它要么是
required
,要么不是,没有条件模型相关。这意味着如果你在REQUIRED_FIELDS
中设置organisation
,那么它会要求它。但是,您可以在经理内部设置条件。在这种情况下,不要在
create_superuser
中使用create_user
。然后,从
MyUser
REQUIRED_FIELDS
中删除organisation
。尽管如此,你的模型还是有一些问题。即,缺少has_perm
、has_module_perms
功能和is_staff
字段。否则,您将无法登录管理页面: