Shortcuts

Convenient shortcuts to manage or check object permissions.

assign_perm

guardian.shortcuts.assign_perm(perm, user_or_group, obj=None)

Assigns permission to user/group and object pair.

Parameters:
  • perm – proper permission for given obj, as string (in format: app_label.codename or codename) or Permission instance. If obj is not given, must be in format app_label.codename or Permission instance.
  • user_or_group – instance of User, AnonymousUser, Group, list of User or Group, or queryset of User or Group; passing any other object would raise guardian.exceptions.NotUserNorGroup exception
  • obj – persisted Django’s Model instance or QuerySet of Django Model instances or list of Django Model instances or None if assigning global permission. Default is None.

We can assign permission for Model instance for specific user:

>>> from django.contrib.sites.models import Site
>>> from guardian.models import User
>>> from guardian.shortcuts import assign_perm
>>> site = Site.objects.get_current()
>>> user = User.objects.create(username='joe')
>>> assign_perm("change_site", user, site)
<UserObjectPermission: example.com | joe | change_site>
>>> user.has_perm("change_site", site)
True

… or we can assign permission for group:

>>> group = Group.objects.create(name='joe-group')
>>> user.groups.add(group)
>>> assign_perm("delete_site", group, site)
<GroupObjectPermission: example.com | joe-group | delete_site>
>>> user.has_perm("delete_site", site)
True

Global permissions

This function may also be used to assign standard, global permissions if obj parameter is omitted. Added Permission would be returned in that case:

>>> assign_perm("sites.change_site", user)
<Permission: sites | site | Can change site>

remove_perm

guardian.shortcuts.remove_perm(perm, user_or_group=None, obj=None)

Removes permission from user/group and object pair.

Parameters:
  • perm – proper permission for given obj, as string (in format: app_label.codename or codename). If obj is not given, must be in format app_label.codename.
  • user_or_group – instance of User, AnonymousUser or Group; passing any other object would raise guardian.exceptions.NotUserNorGroup exception
  • obj – persisted Django’s Model instance or QuerySet of Django Model instances or None if assigning global permission. Default is None.

get_perms

guardian.shortcuts.get_perms(user_or_group, obj)

Returns permissions for given user/group and object pair, as list of strings.

get_user_perms

guardian.shortcuts.get_user_perms(user, obj)

Returns permissions for given user and object pair, as list of strings, only those assigned directly for the user.

get_group_perms

guardian.shortcuts.get_group_perms(user_or_group, obj)

Returns permissions for given user/group and object pair, as list of strings. It returns only those which are inferred through groups.

get_perms_for_model

guardian.shortcuts.get_perms_for_model(cls)

Returns queryset of all Permission objects for the given class. It is possible to pass Model as class or instance.

get_users_with_perms

guardian.shortcuts.get_users_with_perms(obj, attach_perms=False, with_superusers=False, with_group_users=True, only_with_perms_in=None)

Returns queryset of all User objects with any object permissions for the given obj.

Parameters:
  • obj – persisted Django’s Model instance
  • attach_perms – Default: False. If set to True result would be dictionary of User instances with permissions’ codenames list as values. This would fetch users eagerly!
  • with_superusers – Default: False. If set to True result would contain all superusers.
  • with_group_users – Default: True. If set to False result would not contain those users who have only group permissions for given obj.
  • only_with_perms_in – Default: None. If set to an iterable of permission strings then only users with those permissions would be returned.

Example:

>>> 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')
>>> dan = User.objects.create_user('dan', 'dan@example.com', 'dansecret')
>>> assign_perm('change_flatpage', joe, page)
>>> assign_perm('delete_flatpage', dan, page)
>>>
>>> get_users_with_perms(page)
[<User: joe>, <User: dan>]
>>>
>>> get_users_with_perms(page, attach_perms=True)
{<User: joe>: [u'change_flatpage'], <User: dan>: [u'delete_flatpage']}
>>> get_users_with_perms(page, only_with_perms_in=['change_flatpage'])
[<User: joe>]

get_groups_with_perms

guardian.shortcuts.get_groups_with_perms(obj, attach_perms=False)

Returns queryset of all Group objects with any object permissions for the given obj.

Parameters:
  • obj – persisted Django’s Model instance
  • attach_perms – Default: False. If set to True result would be dictionary of Group instances with permissions’ codenames list as values. This would fetch groups eagerly!

Example:

>>> from django.contrib.flatpages.models import FlatPage
>>> from guardian.shortcuts import assign_perm, get_groups_with_perms
>>> from guardian.models import Group
>>>
>>> page = FlatPage.objects.create(title='Some page', path='/some/page/')
>>> admins = Group.objects.create(name='Admins')
>>> assign_perm('change_flatpage', admins, page)
>>>
>>> get_groups_with_perms(page)
[<Group: admins>]
>>>
>>> get_groups_with_perms(page, attach_perms=True)
{<Group: admins>: [u'change_flatpage']}

get_objects_for_user

guardian.shortcuts.get_objects_for_user(user, perms, klass=None, use_groups=True, any_perm=False, with_superuser=True, accept_global_perms=True)

Returns queryset of objects for which a given user has all permissions present at perms.

Parameters:
  • userUser or AnonymousUser instance for which objects would be returned.
  • perms – single permission string, or sequence of permission strings which should be checked. If klass parameter is not given, those should be full permission names rather than only codenames (i.e. auth.change_user). If more than one permission is present within sequence, their content type must be the same or MixedContentTypeError exception would be raised.
  • klass – may be a Model, Manager or QuerySet object. If not given this parameter would be computed based on given params.
  • use_groups – if False, wouldn’t check user’s groups object permissions. Default is True.
  • any_perm – if True, any of permission in sequence is accepted. Default is False.
  • with_superuser – if True and if user.is_superuser is set, returns the entire queryset. Otherwise will only return objects the user has explicit permissions. This must be True for the accept_global_perms parameter to have any affect. Default is True.
  • accept_global_perms – if True takes global permissions into account. Object based permissions are taken into account if more than one permission is handed in in perms and at least one of these perms is not globally set. If any_perm is set to false then the intersection of matching object is returned. Note, that if with_superuser is False, accept_global_perms will be ignored, which means that only object permissions will be checked! Default is True.
Raises:
  • MixedContentTypeError – when computed content type for perms and/or klass clashes.
  • WrongAppError – if cannot compute app label for given perms/ klass.

Example:

>>> from django.contrib.auth.models import User
>>> from guardian.shortcuts import get_objects_for_user
>>> joe = User.objects.get(username='joe')
>>> get_objects_for_user(joe, 'auth.change_group')
[]
>>> from guardian.shortcuts import assign_perm
>>> group = Group.objects.create('some group')
>>> assign_perm('auth.change_group', joe, group)
>>> get_objects_for_user(joe, 'auth.change_group')
[<Group some group>]

The permission string can also be an iterable. Continuing with the previous example:

>>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
[]
>>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'], any_perm=True)
[<Group some group>]
>>> assign_perm('auth.delete_group', joe, group)
>>> get_objects_for_user(joe, ['auth.change_group', 'auth.delete_group'])
[<Group some group>]

Take global permissions into account:

>>> jack = User.objects.get(username='jack')
>>> assign_perm('auth.change_group', jack) # this will set a global permission
>>> get_objects_for_user(jack, 'auth.change_group')
[<Group some group>]
>>> group2 = Group.objects.create('other group')
>>> assign_perm('auth.delete_group', jack, group2)
>>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group']) # this retrieves intersection
[<Group other group>]
>>> get_objects_for_user(jack, ['auth.change_group', 'auth.delete_group'], any_perm) # this retrieves union
[<Group some group>, <Group other group>]

If accept_global_perms is set to True, then all assigned global permissions will also be taken into account.

  • Scenario 1: a user has view permissions generally defined on the model ‘books’ but no object based permission on a single book instance:

    • If accept_global_perms is True: List of all books will be returned.
    • If accept_global_perms is False: list will be empty.
  • Scenario 2: a user has view permissions generally defined on the model ‘books’ and also has an object based permission to view book ‘Whatever’:

    • If accept_global_perms is True: List of all books will be returned.
    • If accept_global_perms is False: list will only contain book ‘Whatever’.
  • Scenario 3: a user only has object based permission on book ‘Whatever’:

    • If accept_global_perms is True: List will only contain book ‘Whatever’.
    • If accept_global_perms is False: List will only contain book ‘Whatever’.
  • Scenario 4: a user does not have any permission:

    • If accept_global_perms is True: Empty list.
    • If accept_global_perms is False: Empty list.

get_objects_for_group

guardian.shortcuts.get_objects_for_group(group, perms, klass=None, any_perm=False, accept_global_perms=True)

Returns queryset of objects for which a given group has all permissions present at perms.

Parameters:
  • groupGroup instance for which objects would be returned.
  • perms – single permission string, or sequence of permission strings which should be checked. If klass parameter is not given, those should be full permission names rather than only codenames (i.e. auth.change_user). If more than one permission is present within sequence, their content type must be the same or MixedContentTypeError exception would be raised.
  • klass – may be a Model, Manager or QuerySet object. If not given this parameter would be computed based on given params.
  • any_perm – if True, any of permission in sequence is accepted
  • accept_global_perms – if True takes global permissions into account. If any_perm is set to false then the intersection of matching objects based on global and object based permissions is returned. Default is True.
Raises:
  • MixedContentTypeError – when computed content type for perms and/or klass clashes.
  • WrongAppError – if cannot compute app label for given perms/ klass.

Example:

Let’s assume we have a Task model belonging to the tasker app with the default add_task, change_task and delete_task permissions provided by Django:

>>> from guardian.shortcuts import get_objects_for_group
>>> from tasker import Task
>>> group = Group.objects.create('some group')
>>> task = Task.objects.create('some task')
>>> get_objects_for_group(group, 'tasker.add_task')
[]
>>> from guardian.shortcuts import assign_perm
>>> assign_perm('tasker.add_task', group, task)
>>> get_objects_for_group(group, 'tasker.add_task')
[<Task some task>]
The permission string can also be an iterable. Continuing with the previous example:
>>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
[]
>>> assign_perm('tasker.delete_task', group, task)
>>> get_objects_for_group(group, ['tasker.add_task', 'tasker.delete_task'])
[<Task some task>]
Global permissions assigned to the group are also taken into account. Continuing with previous example:
>>> task_other = Task.objects.create('other task')
>>> assign_perm('tasker.change_task', group)
>>> get_objects_for_group(group, ['tasker.change_task'])
[<Task some task>, <Task other task>]
>>> get_objects_for_group(group, ['tasker.change_task'], accept_global_perms=False)
[<Task some task>]