Django Viewset Permissions - A Guide to Setting Permissions Per ViewSet Method

Published: June 30, 2023

How can you adjust viewset permissions simply as possible?

Django Viewsets are great for setting up a REST API very quickly with little code. Here's how to set custom permissions for your Django viewset very quickly.

In this case, the 'comments' method within the 'CreationViewSet' requires an 'IsAdminUser' permission, while the rest of the methods within the same ViewSet should remain accessible to all.

How can you achieve this as simply as possible?

Solution: Customizing the get_permissions Method

Django REST Framework allows customization of permissions per action within a ViewSet by overriding the get_permissions method.

Let's walk through some sample Python code that does this:

# views.py
from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Creation
from .serializers import CreationSerializer, CommentSerializer   

class CreationViewSet(viewsets.ModelViewSet):
		queryset = Creation.objects.all()    
    serializer_class = CreationSerializer        
    
    def get_permissions(self):        
    		if self.action == 'comments':            
      			permission_classes = [permissions.IsAdminUser]        
      	else:            
        		permission_classes = [permissions.AllowAny]        
        return [permission() for permission in permission_classes]        

		@action(detail=True, methods=['get'])    
    def comments(self, request, pk=None):        
    		creation = self.get_object()        
        comments = creation.comments.all()        
        serializer = CommentSerializer(comments, many=True)        
        return Response(serializer.data)
  1. We define a class CreationViewSet that extends viewsets.ModelViewSet.
  2. We override the get_permissions method to customize the permission classes based on the action. If the action is 'comments', we restrict the access to admin users only by setting permission_classes = [permissions.IsAdminUser]. For all other actions, we set permission_classes = [permissions.AllowAny] to allow any user to access them.
  3. We define the comments action, which fetches the comments of a specific 'Creation' object and returns them as a response.

This approach offers a clean and elegant solution to apply different permissions per method in a ViewSet.

Subscribe to my free newsletter

Get updates on AI, software, and business.