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(...)
Created
September 8, 2015 11:51
-
-
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
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 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