Skip to content

Instantly share code, notes, and snippets.

@ceolson01
Created March 19, 2016 15:05
Show Gist options
  • Save ceolson01/206139a093b3617155a6 to your computer and use it in GitHub Desktop.
Save ceolson01/206139a093b3617155a6 to your computer and use it in GitHub Desktop.
Django Group Required Mixin
from django.core.exceptions import PermissionDenied
class GroupRequiredMixin(object):
"""
group_required - list of strings, required param
"""
group_required = None
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated():
raise PermissionDenied
else:
user_groups = []
for group in request.user.groups.values_list('name', flat=True):
user_groups.append(group)
if len(set(user_groups).intersection(self.group_required)) <= 0:
raise PermissionDenied
return super(GroupRequiredMixin, self).dispatch(request, *args, **kwargs)
from .mixins import GroupRequiredMixin
from django.views.generic import View
class DemoView(GroupRequiredMixin, View):
group_required = [u'admin', u'manager']
# View code...
@mejl
Copy link

mejl commented Sep 15, 2021

It's not working on CreateView?

@mejl
Copy link

mejl commented Sep 16, 2021

I had to make sure I added GroupRequiredMixin to the left.

before

class CreateView(CreateView, GroupRequiredMixin):
       pass

after:

class CreateView(GroupRequiredMixin, CreateView):
       pass

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment