[Django]-Different Permissions using decorators for each methods inside ModelViewset methods for "list", "create" , "retrieve", "update"

4👍

✅

ModelViewSet inherits Mixin classes and GenericAPIView. The methods list and create are from Mixins hence decorating with permission_classes won’t work. Instead, you can try overriding get_permissions in APIView.

def get_permissions(self):
    if self.request.method == "GET":
        return [IsAuthenticated()]
    elif self.request.method == "POST":
        return [CustomPermission()]
    return [permission() for permission in self.permission_classes]

Note: I am not sure whether above code works or not

2👍

a sample code is shown in official page.
so it might be better not using self.request.method but self.aciton property.

def get_permissions(self):
    """
    Instantiates and returns the list of permissions that this view requires.
    """
    if self.action == 'list':
        permission_classes = [IsAuthenticated]
    else:
        permission_classes = [IsAdmin]
    return [permission() for permission in permission_classes]

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

Leave a comment