django 为什么我得到类型错误:create_superuser()缺少1个必需的位置参数:摘要用户中的“用户名”?

8ftvxx2r  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(138)

我已经写了一个自定义用户模型,当试图创建超级用户得到以下错误**:-**

TypeError: create_superuser() missing 1 required positional argument: 'username'

当我运行创建超级用户的命令时,django没有让我输入用户名。

型号分类:-

class CustomUser(AbstractUser):
    email = models.EmailField(max_length=250, null=False, unique=True)
    name = models.CharField(max_length=50, null=False)
    username = models.CharField(max_length=50, null=False)
    password = models.CharField(max_length=15, null=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

更新日期:-

当我改变USERNAME_FIELDusernameemail它没有要求我输入电子邮件,我得到以下错误:-

TypeError: create_superuser() missing 1 required positional argument: 'email'

这是我所写的一切,我是新的django无法找出我做错了什么。提前感谢。希望很快从你这里。

f0brbegy

f0brbegy1#

你能解释一下你想归档什么吗?并展示一下你是如何调用“create_superuser()”的吗?
如果你从python代码调用它,那么你可能应该提供用户名'manually':

CustomUser.objects.create_superuser(username="some_username")

更新

我认为您的问题在以下问题中有所描述:https://code.djangoproject.com/ticket/26412
要解决您的问题,您必须在username字段中设置null=True,并覆盖模型中的默认UserManager:

class UserProfile(AbstractUser):
    email = models.EmailField(max_length=250, null=False, unique=True)
    name = models.CharField(max_length=50, null=False)
    username = models.CharField(max_length=50, null=True)
    password = models.CharField(max_length=15, null=False)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

自定义用户管理器实现:

from django.apps import apps
from django.contrib.auth.hashers import make_password
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models

class CustomUserManager(UserManager):
    def create_user(self, username=None, email=None, password=None, **extra_fields):
        return super(CustomUserManager, self).create_user(username, email, password, **extra_fields)

    def create_superuser(self, username=None, email=None, password=None, **extra_fields):
        return super(CustomUserManager, self).create_superuser(username, email, password, **extra_fields)

    def _create_user(self, username, email, password, **extra_fields):
        email = self.normalize_email(email)
        GlobalUserModel = apps.get_model(self.model._meta.app_label, self.model._meta.object_name)
        username = GlobalUserModel.normalize_username(username)
        user = self.model(username=username, email=email, **extra_fields)
        user.password = make_password(password)
        user.save(using=self._db)
        return user

检查它是否为您工作,如果是这样,然后请标记为有用的我的答案。

相关问题