Django重写用户模型报错has no attribute 'USERNAME_FIELD'

Django重写用户模型报错has no attribute 'USERNAME_FIELD'

在重写用户模型时报错:AttributeError: type object ‘UserProfile’ has no attribute ‘USERNAME_FIELD’

models.py
- 新建用户模型UserProfile继承自AbstractBaseUser

# -*- encoding:utf-8 -*-

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
# Create your models here.


class UserProfile(AbstractBaseUser):

    nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default="")
    birday = models.DateField(verbose_name=u"生日", null=True, blank=True)
    gender = models.CharField(max_length=5, choices=(("male", u"男"),("female",u"女")), default="female")
    address = models.CharField(max_length=100, default=u"")
    mobile = models.CharField(max_length=11, null=True, blank=True)
    image = models.ImageField(upload_to="image/%Y/%m", default=u"image/default.png", max_length=100)

    class Meta:
        verbose_name = u"用户信息"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.username1234567891011121314151617181920212223

settings.py中也设置了AUTH_USER_MODEL

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'mx_users',

]

AUTH_USER_MODEL = "mx_users.UserProfile"123456789101112

debug时报错:

AttributeError: type object 'UserProfile' has no attribute 'USERNAME_FIELD'1

最后google了一圈才发现解决办法:
答案还是得去官方文档中寻找
https://docs.djangoproject.com/en/1.9/topics/auth/customizing/
这里写图片描述
在模型中新增两行代码,即可解决

    identifier = models.CharField(max_length=40, unique=True)
    USERNAME_FIELD = 'identifier'12

如下:

class UserProfile(AbstractBaseUser):
    identifier = models.CharField(max_length=40, unique=True)
    USERNAME_FIELD = 'identifier'

    nick_name = models.CharField(max_length=50, verbose_name=u"昵称", default="")
    birday = models.DateField(verbose_name=u"生日", null=True, blank=True)
    gender = models.CharField(max_length=5, choices=(("male", u"男"),("female",u"女")), default="female")
    address = models.CharField(max_length=100, default=u"")
    mobile = models.CharField(max_length=11, null=True, blank=True)
    image = models.ImageField(upload_to="image/%Y/%m", default=u"image/default.png", max_length

猜你喜欢

转载自www.cnblogs.com/TMesh/p/11832790.html