gpt4 book ai didi

django - 属性错误 : 'User' object has no attribute 'is_admin'

转载 作者:行者123 更新时间:2023-12-04 00:34:28 24 4
gpt4 key购买 nike

我通过扩展 AbstractBaseUser 自定义了用户模型,用户名仅作为电子邮件 ID 接受。这是模型:

class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email address', unique=True)
first_name = models.CharField('first name', max_length=30, blank=True)
last_name = models.CharField('last name', max_length=30, blank=True)
date_joined = models.DateTimeField('date joined', auto_now_add=True)
is_active = models.BooleanField('active', default=True)
is_staff = models.BooleanField(default=False)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

class Meta:
verbose_name = 'user'
verbose_name_plural = 'users'

def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()

def get_short_name(self):
return self.first_name

def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, [self.email], **kwargs)

上述模型的模型管理器是:
class UserManager(BaseUserManager):
use_in_migrations = True

def _create_user(self, email, password, **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, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)

def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)

if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')

return self._create_user(email, password, **extra_fields)

我可以创建自定义用户,但是当我尝试登录时出现属性错误:
Attribute error: 'User' object has no attribute 'is_admin'

下面是 admin.py 文件
class ProfileInline(admin.StackedInline):
model = Course
can_delete = False
verbose_name_plural = 'Course'
fk_name = 'user'

class CustomUserAdmin(UserAdmin):
inlines = (ProfileInline, )

def get_inline_instances(self, request, obj=None):
if not obj:
return list()
return super(CustomUserAdmin, self).get_inline_instances(request, obj)


admin.site.register(User, CustomUserAdmin)

最佳答案

Django user 模型没有属性 is_admin .
显示错误是因为在您的代码中某处(可能是登录 View ?)您正在调用 user.is_admin .找到并删除它,或使用 user.is_staff/user.is_superuser反而。

关于django - 属性错误 : 'User' object has no attribute 'is_admin' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45862889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com