Skip to content

Instantly share code, notes, and snippets.

@respondcreate
Created March 13, 2016 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save respondcreate/3abb4fa450ef95ef7716 to your computer and use it in GitHub Desktop.
Save respondcreate/3abb4fa450ef95ef7716 to your computer and use it in GitHub Desktop.
from django.http import HttpResponseForbidden
class RequiredGroupMixin(object):
"""
Ensure only logged in users who belong to a particular group (or groups)
can access this view.
To use this Mixin, just include it as a subclass to your view and add a
new attribute, `restrict_to_groups`, as an iterable of allowed group names.
For example, if you want to restrict this view to only users in the group
'Students' you'd set `restrict_to_groups` like so:
restrict_to_groups = ('Students',)
"""
def dispatch(self, request, *args, **kwargs):
if hasattr(self, 'restrict_to_groups'):
allowed_groups = request.user.groups.filter(
name__in=self.restrict_to_groups
)
if not allowed_groups:
forbidden_message = 'You are not allowed to view this page.'
if request.user.is_superuser is True:
forbidden_message = (
'Only users that belong to the following groups may '
'access this page: {}'.format(
', '.join(self.restrict_to_groups)
)
)
return HttpResponseForbidden(forbidden_message)
return super(RequiredGroupMixin, self).dispatch(
request, *args, **kwargs
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment