Skip to content

Instantly share code, notes, and snippets.

@ceolson01
Created March 19, 2016 15:05
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • 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...
@peterretief
Copy link

peterretief commented Jul 20, 2018

I had to change is_authenticated() to is_authenticated using python3 and django2

@juanhenaoparra
Copy link

Bro, you have saved my life.

@sogorich
Copy link

Excellent and convenient. There is one problem, of course, namely when the user is being checked for authorization. If the user is anonymous, meaning that they did not authenticate on the site, they will throw a TypeError exception, not a Permission denied call.

However, if someone will use it without difficulty, everything will be corrected. Overall, thank you for making my life a little easier :)

@YaidelLuis
Copy link

YaidelLuis commented Mar 1, 2021

Hola, excelente la solución al problema, solo me gustaría saber como puedo retornar en vez del error 403 forbidden, un mensaje personalizado como por ejemplo que ese usuario no tiene acceso a esa url, gracias

@lucas-montes
Copy link

lucas-montes commented Mar 10, 2021

Hola, excelente la solución al problema, solo me gustaría saber como puedo retornar en vez del error 403 forbidden, un mensaje personalizado como por ejemplo que ese usuario no tiene acceso a esa url, gracias

En tus templates puedes crear un 403.html y customizarlo como quieras. Al aparecer el error le redireccionará al template que has creado. Ahí puedes mostrar tu mensaje. Otra solución es cambiar "raise PermissionDenied" por un return redirect y los mandas donde quieras.

@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