8

我尝试创建一个自定义用户模型来向用户添加一些自定义字段。我使用了 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)

对此有何建议?谢谢!

4

2 回答 2

29

您不必让您的类从 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
于 2014-02-25T22:48:31.643 回答
9

让类ShopUser继承PermissionsMixin如下:

class ShopUser(AbstractBaseUser, PermissionsMixin):

这将添加该is_superuser字段,并且应该与管理 UI 很好地配合使用。

你的create_superuser方法应该设置user.is_superuser = True.

最后,您应该为您的班级实施get_full_name和。get_short_nameShopUser

更多信息:在 Django 中自定义身份验证

于 2013-04-23T00:35:18.007 回答