这个错误意味着什么?
AttributeError:'CustomUser'对象没有属性'first_name'
custom_user / models.py
from time import timezone
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.core.mail import send_mail
from django.utils.translation import ugettext_lazy as _
from datetime import datetime
now = datetime.now()
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email,
is_staff=is_staff, is_active=True,
is_superuser=is_superuser, last_login=now,
**extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
return self._create_user(email, password, False, False, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
return self._create_user(email, password, True, True, **extra_fields)
class CustomUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(max_length=254, unique=True)
email = models.EmailField(blank=True, unique=True)
address1 = models.CharField(max_length=254, blank=True)
address2 = models.CharField(max_length=254, blank=True)
area_code = models.CharField(max_length=20, blank=True)
country_code = models.CharField(max_length=10, blank=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'address1', 'address2', 'area_code', 'country_code']
objects = CustomUserManager()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
def email_user(self, subject, message, from_email=None, **kwargs):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email], **kwargs)
我一直在尝试为普通用户和超级用户创建自定义用户注册表单,但我仍然无法以超级用户/管理员身份登录。我也无法注册任何用户,因为它没有连接到db。我按照本教程了解如何创建自定义用户https://www.youtube.com/watch?v=5x97gGspzjY,我设法做到了。我只是无法以管理员身份登录,无法注册任何用户。究竟下一步是什么
答案 0 :(得分:1)
据我所知,您的自定义模型(first_name
)中没有CustomUser
属性。这就是
AttributeError:' CustomUser'对象没有属性' first_name'
告诉你。
看看你的CustomUser
课程。它定义了username
,email
等,但它没有在任何地方定义first_name
。但是,您尝试在多种方法中引用first_name
(未针对类/模型定义)(即get_full_name()
,get_short_name()
。
尝试定义它并查看错误是否仍然存在。