我尝试创建自定义用户模型,以便向用户添加一些自定义字段。我在django 1.5中使用了基于AbstractBaseUser的新方法。除管理员面板外,一切(登录)都有效。登录管理界面时,出现以下错误:
AttributeError at /admin/
'ShopUser' object has no attribute 'is_superuser'
这是我的模特:
from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser
from django.contrib import auth
class ShopUserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise ValueError("We need an e-mail here...")
user = self.model(
email = ShopUserManager.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
user = self.create_user(
email,
password = password,
)
user.is_admin = True
user.is_staff = True
user.save(using=self._db)
return user
class ShopUser(AbstractBaseUser):
email = models.EmailField(
verbose_name = 'e-mail address',
max_length = 255,
unique = True,
db_index = True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
objects = ShopUserManager()
USERNAME_FIELD = 'email'
# REQUIRED_FIELDS = ['']
def __unicode__(self):
return self.email
def has_perms(self, perm_list, obj=None):
"""
Returns True if the user has each of the specified permissions. If
object is passed, it checks if the user has all required perms for this
object.
"""
for perm in perm_list:
if not self.has_perm(perm, obj):
return False
return True
def has_module_perms(self, app_label):
"""
Returns True if the user has any permissions in the given app label.
Uses pretty much the same logic as has_perm, above.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
return _user_has_module_perms(self, app_label)
对此有何建议?谢谢!
答案 0 :(得分:27)
您不必让您的类继承PermissionsMixin。
我遇到了同样的问题,我通过在我的用户类中添加一些必需的方法来修复它(在你的情况下是ShopUser)。
class ShopUser(AbstractBaseUser):
...
def get_full_name(self):
return self.fullname
def get_short_name(self):
return self.shortname
@property
def is_superuser(self):
return self.is_admin
@property
def is_staff(self):
return self.is_admin
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return self.is_admin
答案 1 :(得分:9)
让班级ShopUser
继承PermissionsMixin
,如此:
class ShopUser(AbstractBaseUser, PermissionsMixin):
这将添加is_superuser
字段,并且可以很好地与管理UI一起使用。
您的create_superuser
方法应设置user.is_superuser = True
。
最后,您应该为get_full_name
课程实施get_short_name
和ShopUser
。