如何在django监护人中获取对象具有特定权限的所有用户?

时间:2013-02-28 14:35:44

标签: django-permissions django-guardian

from guardian.shortcuts import get_objects_for_user

但是

from guardian.shortcuts import get_users_for_object

感谢。

4 个答案:

答案 0 :(得分:3)

实际上有一个快捷方式

http://django-guardian.readthedocs.io/en/stable/api/guardian.shortcuts.html#get-users-with-perms

>>> from django.contrib.flatpages.models import FlatPage
>>> from django.contrib.auth.models import User
>>> from guardian.shortcuts import assign_perm, get_users_with_perms
>>>
>>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
>>> joe = User.objects.create_user('joe', 'joe@example.com', 'joesecret')
>>> assign_perm('change_flatpage', joe, page)
>>>
>>> get_users_with_perms(page)
[<User: joe>]
>>>
>>> get_users_with_perms(page, attach_perms=True)
{<User: joe>: [u'change_flatpage']}

答案 1 :(得分:1)

这样的事情看起来不错:https://github.com/lukaszb/django-guardian/blob/master/guardian/shortcuts.py#L214

    >>> from django.contrib.flatpages.models import FlatPage
    >>> from django.contrib.auth.models import User
    >>> from guardian.shortcuts import assign_perm, get_users_with_perms
    >>>
    >>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
    >>> joe = User.objects.create_user('joe', 'joe@example.com', 'joesecret')
    >>> assign_perm('change_flatpage', joe, page)
    >>>
    >>> get_users_with_perms(page)
    [<User: joe>]
    >>>
    >>> get_users_with_perms(page, attach_perms=True)
    {<User: joe>: [u'change_flatpage']}

答案 2 :(得分:1)

这是我的解决方法。这是模型方法。你可以将它封装在mixin中。

def get_users_with_perm(self, permission):
    '''
    Returns list of users(worn:not QuerySet) with specific permission for this object
    :param permission: permission string
    '''

    anyperm = get_users_with_perms(self, attach_perms=True)
    result = []
    for user, perms in anyperm.iteritems():
        if permission in perms: result.append(user)
    return result

答案 3 :(得分:0)

我使用内置的get_users_with_perms()快捷方式解决了这个问题,然后使用python字典理解功能返回了对给定对象具有特定权限的用户对象列表。

from django.contrib.flatpages.models import FlatPage
from django.contrib.auth.models import User
from guardian.shortcuts import assign_perm, get_users_with_perms

创建页面对象并授予用户“ Joe” change_flatpage权限

page = FlatPage.objects.create(title='Some page', path='/some/page/')
joe = User.objects.create_user('joe', 'joe@example.com', 'joesecret')
assign_perm('change_flatpage', joe, page)

使用Guardian查找对特定页面对象具有任何权限的用户

perms = get_users_with_perms(page, attach_perms=True)

使用python字典理解功能返回包含特定权限的新用户列表

perm_name = "change_flatpage"
change_flatpage_user_list = [ k for k, v in perms.items() if perm_name in v ]