Search code examples
djangodjango-rest-frameworkdjango-viewspython-decoratorsdjango-permissions

Different Permissions using decorators for each methods inside ModelViewset methods for "list", "create" , "retrieve", "update"


I want to add different permissions for different methods of ModelViewset class using decorator.

I tried:

class abcd(viewsets.ModelViewSet):

    @permission_classes(IsAuthenticated,))
    def list(self, request, format=None):
        try:


    @permission_classes(CustomPermission,))
    def create(self, request, format=None):
        try:

But it isn't working. I also tried using @method_decorator. That didn't worked either.

I know we can do in the following way:

def get_permissions(self):
    if self.action == 'create':
        return [IsAuthenticated(), ]        
    return super(abcd, self).get_permissions()

But I was wondering if we can achieve this using decorators for Django Rest Framework.


Solution

  • 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