[Answered ]-Change permission on the basis of button chosen in Django

1👍

You can override the viewsets get_permissions() method and define a permission for each of the viewset actions

https://www.django-rest-framework.org/api-guide/viewsets/#viewset-actions

For example, I did a quick test with the following:

class MyModelViewset(viewsets.ModelViewSet):
    serializer_class = MyModelSerializer
    model = MyModel

    def get_permissions(self):
        if self.action == "create":
            self.permission_classes = [IsNotSuperUser]
        elif self.action == "update":
            self.permission_classes = [IsTeacher]
        elif self.action == "partial_update":
            self.permission_classes = [IsNotSuperUser]
        elif self.action == "list":
            self.permission_classes = [IsSuperUser, IsAuthenticated]
        elif self.action == "retrieve":
            self.permission_classes = [IsSuperUser, IsAuthenticated]
        return super(self.__class__, self).get_permissions()
   

With this you can control permissions for each of the HTTP verbs.

Leave a comment