django.core.exceptions.FieldDoesNotExist:用户没有名为“username”的字段

euoag5mw  于 2022-12-27  发布在  Go
关注(0)|答案(4)|浏览(250)

我尝试自定义django的AbstractUser,当我尝试将username重置为None时,我遇到了如下异常:

"django.core.exceptions.FieldDoesNotExist: User has no field named 'username'".

下面是我的代码:

class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        if not email:
            raise ValueError("L'adresse e-mail donnée doit etre definie")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password, **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, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", 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 User(AbstractUser):
    username = None
    email = models.EmailField('email adress', unique=True)
    telephone = models.CharField(max_length=20)
    REQUIRED_FIELDS = []

我能做些什么来解决这个问题?

0x6upsns

0x6upsns1#

如果您在项目中使用django-allauth,也可能会导致此问题。要修复此问题,您需要在settings.py中将ACCOUNT_USER_MODEL_USERNAME_FIELD定义为None。请参阅questionallauth documentation以了解更多信息。

ACCOUNT_USER_MODEL_USERNAME_FIELD = None
58wvjzkj

58wvjzkj2#

您还没有在代码中为USERNAME_FIELD设置值。必须将其设置为唯一标识用户示例的字段。AbstractUser将其设置为'username',因此您会收到错误。您可以将其设置为'email'来解决问题:

class User(AbstractUser):
    username = None
    email = models.EmailField('email adress', unique=True)
    telephone = models.CharField(max_length=20)
    # set below value
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
chhqkbe1

chhqkbe13#

将用户名设置为None的原因是什么?
用户模型必须具有唯一字段(如用户名、电子邮件或电话号码)以标识用户。
如果你想覆盖用户的模型,你应该提供这样的唯一字段,将其标记为用户名字段,并设置django设置变量AUTH_USER_MODEL来定义你的定制模型。
大概是这样的

# model
class User(AbstractUser):
    username = models.CharField(max_length=32, unique=True)  # or something else
    ...

    USERNAME_FIELD = 'username'

# settings
AUTH_USER_MODEL = 'users.User'
u5rb5r59

u5rb5r594#

我看你想用电子邮件来验证身份。
正如documentation所述,您必须在设置文件中添加:

ACCOUNT_AUTHENTICATION_METHOD ="email"

但首先,您必须在模型中添加:

class User(AbstractUser):
    username = None
    email = models.EmailField('email adress', unique=True)
    telephone = models.CharField(max_length=20)
    REQUIRED_FIELDS = []
    USERNAME_FIELD = "email"

相关问题