Django custom user model gives error: TypeError: create_superuser() got an unexpected keyword argument 'username'

Django custom user model gives error: TypeError: create_superuser() got an unexpected keyword argument 'username'

我正在根据以下教程创建 Django 自定义用户:

class UserProfileManager(BaseUserManager):
    """Helps Django work with our custom user model."""

    def create_user(self, email, name, password=None):
        """Creates a user profile object."""

        if not email:
            raise ValueError('Users must have an email address.')

        email = self.normalize_email(email)
        user = self.model(email=email, username=name)

        user.user_id = -1
        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_superuser(self, email, name, password):
        """Creates and saves a new superuser with given details."""

        user = self.create_user(email = email, name = name, password = password)

        user.is_superuser = True

        user.save(using=self._db)


class CustomUser(AbstractBaseUser, PermissionsMixin):
    """Represents a user profile inside our system"""

    email = models.EmailField(max_length=255, unique=True)
    username = models.CharField(max_length=255, unique=True)
    user_id = models.IntegerField()

    objects = UserProfileManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.email

当我尝试创建超级用户时出现以下错误:

TypeError: create_superuser() got an unexpected keyword argument 'username'

但是,如果我将 "username" 字段的名称更改为 "name",我将能够创建超级用户而不会出现错误! 有谁知道为什么我不能将字段命名为 "name" 以外的任何名称?

在您的函数中,您将 username 参数定义为 name:

...
def create_superuser(self, email, name, password):
    ...

在你的代码的其他部分甚至在 django 本身。也许有人用 username='some-username'.

调用你的 create_superuser 函数