Django1.9重写用户模型报错has no attribute 'USERNAME_FIELD'

在使用Django框架时,重写用户模型遇到AttributeError异常,详细介绍了错误原因及解决方案,通过添加唯一标识符字段并指定USERNAME_FIELD属性,成功解决自定义用户模型的问题。

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)

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值