create_user()缺少1个必需的位置参数:“用户名”

时间:2020-09-30 21:06:06

标签: python django django-models django-users django-custom-user

我删除了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个必需的位置参数:“用户名” 我该如何解决?

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管理员。