如何在自定义用户模型中使用django-guardian

时间:2018-07-03 17:40:32

标签: django python-3.x django-guardian

我正在使用django-guardian检查用户的对象权限。在我的特殊情况下,我扩展了用户模型。 在我的models.py中,我扩展了用户模型,如下所示: enter image description here

class User(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    active = models.BooleanField(default=True)
    staff = models.BooleanField(default=False) 
    admin = models.BooleanField(default=False) 

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [] # Email & Password are required by default.

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        return self.staff

    @property
    def is_admin(self):
        "Is the user a admin member?"
        return self.admin

    @property
    def is_active(self):
        "Is the user active?"
        return self.active

在我的对象模型中,我添加了一个用于许可的Meta类: enter image description here

class task(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        permissions = (
            ('view_task', 'View task'),
        )

    def __str__(self):
        return self.name

在进行makemigrations和迁移之后,当我在python manage.py shell中进行测试时,它将始终在用户模型中调用has_perm函数,并返回该函数的值,即True。

>>>from myapp.models import User, task
>>>setuser = User.objects.get(email = 'joe@gmail.com')
>>>task = exclusionDomain.objects.get(name = 'task1')
>>>setuser.has_perm('view_task', task)

如何解决此问题?还是有关于如何在自定义用户模型中使用监护人的有用教程?

1 个答案:

答案 0 :(得分:1)

如果有人遇到相同的问题。解决方法如下:

使用AbstractUser代替使用AbstractBaseUser。 AbstractBaseUser与django-guardian不兼容。并且根据监护人文档,使用AbstractUser的扩展用户模型应该可以。而且对我也有用。

这里是有关如何使用AbstractUser扩展用户模型的教程: https://docs.python.org/3.6/library/datetime.html