Skip to content

Instantly share code, notes, and snippets.

@jperelli
Created September 8, 2015 11:51
Show Gist options
  • Save jperelli/d57c9ecae304fb60408b to your computer and use it in GitHub Desktop.
Save jperelli/d57c9ecae304fb60408b to your computer and use it in GitHub Desktop.
Decorator to easily add permission requirements to a custom method in a viewset in django-rest-framework

Usage

class SomeViewSet(viewsets.ModelViewSet):
    queryset = models.Some.objects.all()
    serializer_class = SomeSerializer

    @detail_route(methods=['post'])
    @route_permissions('some_app.some_permission')
    def custom_method(self, request, pk=None):
      return Response(...)
from rest_framework.exceptions import PermissionDenied
def route_permissions(permission):
""" django-rest-framework permission decorator for custom methods """
def decorator(drf_custom_method):
def _decorator(self, *args, **kwargs):
if self.request.user.has_perm(permission):
return drf_custom_method(self, *args, **kwargs)
else:
raise PermissionDenied()
return _decorator
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment