首页 > 解决方案 > 我正在尝试更改为自定义用户模型,但出现错误

问题描述

我正在尝试将 Django 用户模型更改为自定义用户模型,但出现错误

如何解决错误?谢谢你让我知道~!

step1 设置.py

AUTH_USER_MODEL = 'accounts.User'

step2 账户/models.py

from django.contrib.auth.models import AbstractBaseUser
from django.db import models

# Create your models here.
class User(AbstractBaseUser):
    email = models.EmailField(blank=True)
    website_url = models.URLField(blank=True)

step3 迁移时出现如下错误

(askcompany) C:\my_django\askcompany>python manage.py makemigrations

错误信息:

  File "C:\Users\hyunsepk\AppData\Local\conda\conda\envs\askcompany\lib\site-packages\django\contrib\auth\checks.py", line 39, in check_user_model
    if cls.USERNAME_FIELD in cls.REQUIRED_FIELDS:
AttributeError: type object 'User' has no attribute 'USERNAME_FIELD'

step4 我改成了这个,但是又出现了一个错误

帐户/模型.py

class User(AbstractBaseUser):
    """User model."""

    username = None
    email = models.EmailField(blank=True)
    website_url = models.URLField(blank=True)


    USERNAME_FIELD = 'email'

错误信息:

(askcompany) C:\my_django\askcompany>python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\hyunsepk\AppData\Local\conda\conda\envs\askcompany\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\hyunsepk\AppData\Local\conda\conda\envs\askcompany\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    django.setup()
  File "C:\Users\hyunsepk\AppData\Local\conda\conda\envs\askcompany\lib\site-packages\django\__init__.py", line 24, in setup

(askcompany) C:\my_django\askcompany>python manage.py makemigrations
SystemCheckError: System check identified some issues:

ERRORS:
accounts.User: (auth.E003) 'User.email' must be unique 
because it is named as the 'USERNAME_FIELD'.

step5 我再次改成这个

class User(AbstractUser):
    """User model."""

    email = models.EmailField(blank=True, unique=True)
    website_url = models.URLField(blank=True)


    USERNAME_FIELD = 'email'

另一个错误信息是这个

ERRORS:
accounts.User: (auth.E002) The field named as the 'USERNAME_FIELD' for a custom user model must not be included in 'REQUIRED_FIELDS'.

标签: django

解决方案


错误说 USERNAME_FIELD 没有属性。因此,如果您不想要名称字段,您可以告诉 Django,您将像这样使用电子邮件字段作为 USERNAME_FIELD。

class User(AbstractBaseUser):
    """User model."""

    username = None
    email = models.EmailField(unique=True,blank=True)
    website_url = models.URLField(blank=True)


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

查看此文档,这将解释更多。

https://www.fomfus.com/articles/how-to-use-email-as-username-for-django-authentication-removing-the-username


推荐阅读