django-guardian - meaning of (User, 'username', 'username')

304 Views Asked by At

Can anyone explain me, what does (User, 'username', 'username') and (User, 'username', 'username', 'groups__name', 'group_name') mean?

@permission_required('auth.change_user', return_403=True)
def my_view(request):
    return HttpResponse('Hello')

@permission_required('auth.change_user', (User, 'username', 'username'))
def my_view(request, username):
    user = get_object_or_404(User, username=username)
    return user.get_absolute_url()

@permission_required('auth.change_user',
    (User, 'username', 'username', 'groups__name', 'group_name'))
def my_view(request, username, group_name):
    user = get_object_or_404(User, username=username,
        group__name=group_name)
    return user.get_absolute_url()

Taken here: http://pythonhosted.org/django-guardian/api/guardian.decorators.html

1

There are 1 best solutions below

0
On

From the docs:

Optionally, instances for which check should be made may be passed as an second argument or as a tuple parameters same as those passed to get_object_or_404 but must be provided as pairs of strings.

So if you want to check permission of one User model instance, you can pass the tuple in order (ModelName, argname, varname) (note that argname and varname should be in pair) like:

(User, 'username', 'username')

It's the same as parameters in get_object_or_404() function:

get_object_or_404(User, username=username)

And similar if you have tuple (User, 'username', 'username', 'groups__name', 'group_name')...

You can check the source code for more understanding: https://github.com/lukaszb/django-guardian/blob/master/guardian/decorators.py#L74