This snippet provides a @group_required decorator. You can pass in multiple groups, for example:
@group_required('admins','editors')
def myview(request, id):
...
Note: the decorator is based on the snippet here but extends it checking first that the user is logged in before testing for group membership - user_passes_test does not check for this by default.
It is important to check that the user is first logged in, as anonymous users trigger an AttributeError when the groups filter is executed.
1 2 3 4 5 6 7 8 9 10 | from django.contrib.auth.decorators import user_passes_test
def group_required(*group_names):
"""Requires user membership in at least one of the groups passed in."""
def in_groups(u):
if u.is_authenticated():
if bool(u.groups.filter(name__in=group_names)) | u.is_superuser:
return True
return False
return user_passes_test(in_groups)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 4 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
For using it in urls.py shoud write
#
Avoid a potentially unnecessary database hit by swapping the position of is_superuser and the groups.filter.
#
To support modern django rest framework APIViews (class-based views).
@method_decorator(group_required('groupa', 'groupb'))
#
Since version >=1.10
is_authenticated
is an attribute instead of a method. For newer versions you have to remove parenthesis:(https://docs.djangoproject.com/en/1.10/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated)
#
Line 7: I have had to correct "|" by "or".
(Python 3.7, Django 3.2)
#
Please login first before commenting.