Django1.9.5
Python3.6
在重写用户模型时报错:AttributeError: type object ‘UserProfile’ has no attribute ‘USERNAME_FIELD’
models.py
- 新建用户模型UserProfile继承自AbstractBaseUser
from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractBaseUser
class UserInfo(AbstractBaseUser):
phone = models.CharField(max_length=11)
settings.py中也设置了AUTH_USER_MODEL
AUTH_USER_MODEL = "mx_users.UserProfile"
执行创建表时报错
AttributeError: type object 'UserProfile' has no attribute 'USERNAME_FIELD'
解决方案
在模型中新增两行代码,即可解决
identifier = models.CharField(max_length=40, unique=True)
USERNAME_FIELD = 'identifier'
如下:
from django.db import models
# Create your models here.
from django.contrib.auth.models import AbstractBaseUser
class UserInfo(AbstractBaseUser):
identifier = models.CharField(max_length=40, unique=True)
USERNAME_FIELD = 'identifier'
phone = models.CharField(max_length=11)
在使用Django框架时,重写用户模型遇到AttributeError异常,详细介绍了错误原因及解决方案,通过添加唯一标识符字段并指定USERNAME_FIELD属性,成功解决自定义用户模型的问题。
10万+

被折叠的 条评论
为什么被折叠?



