Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework - Different permission per methods within same view

So I've seen a couple of questions here on SO which are similar, but not quite what I'm looking for.

I'm trying to have different permissions per method within the same view. What I currently have:

class MyViewSet(viewsets.ViewSet):
    # User must be authenticated
    permission_classes = (IsAuthenticated,)

    def list(self, request):
        ...

    # User must be admin
    def create(self, request):
        ...

    def retrieve(self, request):
        ...

Basically I'm trying to ensure that only admins can call the create method. I've looked at creating custom permissions, but that applies accross the viewset, which is not quite what I want.

like image 700
Andrew Avatar asked Mar 12 '23 22:03

Andrew


1 Answers

I think there is no inbuilt solution for that. But you can achieve this by overriding the get_permissions method.

class MyViewSet(viewsets.ViewSet):

    permission_classes_by_action = {
        "default": [IsAuthenticated],
        "retrieve": [AllowAny],
    }

    def get_permissions(self):
        try:
            # return permission_classes depending on `action`
            return [
                permission()
                for permission in self.permission_classes_by_action[self.action]
            ]
        except KeyError:
            # action is not set return default permission_classes
            return [
                permission()
                for permission in self.permission_classes_by_action["default"]
            ]
like image 200
ilse2005 Avatar answered Apr 17 '23 11:04

ilse2005