Created
March 19, 2016 15:05
-
-
Save ceolson01/206139a093b3617155a6 to your computer and use it in GitHub Desktop.
Django Group Required Mixin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from .mixins import GroupRequiredMixin | |
from django.views.generic import View | |
class DemoView(GroupRequiredMixin, View): | |
group_required = [u'admin', u'manager'] | |
# View code... |
It's not working on CreateView?
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
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.