一切都很好,直到我删除数据库并再次运行迁移。现在,我无法再次创建超级用户。
我得到的错误是:
TypeError:create_user((缺少1个必需的位置参数:"组">
我从:python3 manage.py从终端创建超级用户。
任何人都面临同样的问题,有什么解决方案可以修复错误吗?
型号.py
class CustomUserManager(BaseUserManager):
def create_user(self, email: str, password: str, group: Group, **extra_fields):
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
if group is not None:
group.user_set.add(user)
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(email, password, **extra_fields)
class CustomUser(AbstractUser):
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
username = models.CharField(max_length=30, blank=True, default='')
is_superuser = models.BooleanField(default=True)
is_admin = models.BooleanField(default=True)
is_employee = models.BooleanField(default=True)
is_headofdepartment = models.BooleanField(default=True)
is_reception = models.BooleanField(default=True)
is_patient = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=True)
表单.py
class UserForm(ModelForm):
group = forms.ModelChoiceField(queryset=Group.objects.all())
#temp['group']=request.POST.get('group')
#role = forms.ChoiceField(choices=ROLE_CHOICES, label='', widget=forms.RadioSelect(attrs={}))
class Meta:
model = CustomUser
fields = [
'email',
'password',
'group',
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['group'] = ModelChoiceField(
queryset=Group.objects.all(),
empty_label='No group'
)
create_superuser管理命令使用orignalUser.objects.create_User函数。
您添加了一个必需的位置参数。create_superuser命令在调用时不会放入任何组参数。
如果你真的需要,你应该让这个组参数是可选的。
from typing import Optional
class CustomUserManager(BaseUserManager):
def create_user(self,
email: str,
password: str,
group: Optional[Group] = None,
**extra_fields):
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
if group is not None:
group.user_set.add(user)
return user