Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get all users an object has specific permissions to in django guardian?

There is

from guardian.shortcuts import get_objects_for_user

But what about

from guardian.shortcuts import get_users_for_object

Thanks.

like image 713
Natim Avatar asked Feb 28 '13 14:02

Natim


2 Answers

Actually there is a shortcut for that

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', '[email protected]', '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']}
like image 99
Javier Campos Avatar answered Sep 20 '22 04:09

Javier Campos


This is my workaround. This is Model method. You can encapsulate it in 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
like image 29
Lord_JABA Avatar answered Sep 21 '22 04:09

Lord_JABA