Different permissions for different actions with django-rest-framework

Fanciful moment

The property permission_classes of an viewset controls the permission of all actions, which means all actions have same permissions. Sometimes we want to give a different permission to an action of the viewset from another one. Here is the solution for this.

Custom permission

There is a function named get_permissions() in viewset class. If we want to give a different permission for an action, we can override this function. Here is the sample code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from rest_framework import viewsets
from ...

class TestViewSet(viewsets.ModelViewSet):
model = Test
serializer_class = TestSerializer
permission_classes = [IsAuthenticated]

def get_permissions(self):
"""
Only admin can delete the instance
"""
# action is the function name
if self.action == 'destory':
self.permission_classes = [IsAdminUser]
return super().get_permissions()

def destory(self):
# do something

References:
[1] https://www.django-rest-framework.org/api-guide/viewsets/#introspecting-viewset-actions


Different permissions for different actions with django-rest-framework
https://r-future.github.io/post/custom-permission-for-different-action-in-an-viewset/
Author
Future
Posted on
July 12, 2022
Licensed under