django - 我正在尝试更改为自定义用户模型,但出现错误
问题描述
我正在尝试将 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'.
解决方案
错误说 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']
查看此文档,这将解释更多。
推荐阅读
- docker - Nginx proxy and docker 502 bad gateway
- java - How to determine if a thread is main thread in Java?
- html - 使用引导网格通过 ngFor 显示来自 api 调用的项目
- docker - 如何限制kafka-streams中的rocksdb内存使用
- c++ - 使用 enable_if 澄清成员函数模板特化
- python - 如何在对象类型为的输出中查找带有冒号的特定文本
在蟒蛇? - java - 单体架构和微服务架构的 API/Service 消费是否存在技术差异?
- javascript - 数字自动收报机计数到值然后停止
- docker - 用户应该拥有哪些权限才能公开 docker 容器端口?
- mongodb - 找不到类 com.mongodb.client.model.geojson.Point 的编解码器