permission_required(perm, lookup_variables=None, **kwargs)¶
Decorator for views that checks whether a user has a particular permission enabled.
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_404but must be provided as pairs of strings. This way decorator can fetch i.e.
Userinstance based on performed request and check permissions on it (without this, one would need to fetch user instance at view’s logic and check permission inside a view).
- login_url – if denied, user would be redirected to location set by
this parameter. Defaults to
- redirect_field_name – name of the parameter passed if redirected.
- return_403 – if set to
Truethen instead of redirecting to the login page, response with status code 403 is returned (
django.http.HttpResponseForbiddeninstance or rendered template - see
GUARDIAN_RENDER_403). Defaults to
- accept_global_perms – if set to
True, then object level permission would be required only if user does NOT have global permission for target model. If turned on, makes this decorator like an extension over standard
django.contrib.admin.decorators.permission_requiredas it would check for global permissions first. Defaults to
@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): ''' auth.change_user permission would be checked based on given 'username'. If view's parameter would be named ``name``, we would rather use following decorator:: @permission_required('auth.change_user', (User, 'username', 'name')) ''' 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): ''' Similar to the above example, here however we also make sure that one of user's group is named same as request's ``group_name`` param. ''' user = get_object_or_404(User, username=username, group__name=group_name) return user.get_absolute_url()
- login_url – if denied, user would be redirected to location set by this parameter. Defaults to
permission_required_or_403(perm, *args, **kwargs)¶
Simple wrapper for permission_required decorator.
Standard Django’s permission_required decorator redirects user to login page in case permission check failed. This decorator may be used to return HttpResponseForbidden (status 403) instead of redirection.
The only difference between
permission_requireddecorator is that this one always set