This snippet provides a @group_required decorator. You can pass in multiple groups, for example:
@group_required('admins','editors') def myview(request, id): ...
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
- "Magic Link" Management Command by webology 4 months, 1 week ago
- Closest ORM models to a latitude/longitude point by simonw 4 months, 1 week ago
- Log the time taken to execute each DB query by kennyx46 4 months, 1 week ago
- django database snippet by ItsRLuo 4 months, 2 weeks ago
- Serialize a model instance by chriswedgwood 5 months, 2 weeks ago