我删除了username
字段是因为我希望用户能够使用其电子邮件地址登录,所以我在models.py
中有此地址:
class CustomUser(AbstractUser):
USER_TYPE = ((1, 'HOD'), (2, 'Staff'), (3, 'Student'))
username = None
email = models.EmailField(unique=True)
user_type = models.CharField(default=1, choices=USER_TYPE, max_length=1)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Student(models.Model):
admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
gender = models.CharField(max_length=1, choices=GENDER)
address = models.TextField()
profile_pic = models.ImageField(upload_to='media')
session_start_year = models.DateField(null=True)
session_end_year = models.DateField(null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
在我的views.py
中,我尝试了:
user = CustomUser.objects.create_user(email=email, password=password, user_type=3, first_name=first_name, last_name=last_name)
但是我有 create_user()缺少1个必需的位置参数:“用户名” 我该如何解决?
答案 0 :(得分:1)
您需要编写https://www.baeldung.com/properties-with-spring来重新实现create_user
方法。
您可以因此实现CustomUserManager
:
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import UserManager
class CustomUserManager(UserManager):
def _create_user(self, email, password, **extra_fields):
email = self.normalize_email(email)
user = CustomUser(email=email, **extra_fields)
user.password = make_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
assert extra_fields['is_staff']
assert extra_fields['is_superuser']
return self._create_user(email, password, **extra_fields)
class CustomUser(AbstractUser):
# …
objects = CustomUserManager()
,然后您将此管理员注册为objects
管理员。