How can I disable authentication for GET method in django modelviewset?

Viewed 217

I have written one router url and modelviewset like below: **router.register(r'TestViewSet', views.TestViewSet)

**class TestViewSet(viewsets.ModelViewSet): queryset = Test.objects.all() serializer_class = TestSerializer for this class, I want to disable authentication for GET method. Pls give some solution

1 Answers

Well to disable authentication only on the GET method of the ModelViewSet, we are required to override the permission class based on the HTTP method.

To achieve this, try following

from rest_framework import permissions

...

class TestViewSet(viewsets.ModelViewSet):

...

def get_permissions(self):
    """Returns the permission based on the type of action"""

    if self.action == "list":
        return [permissions.AllowAny()]

    return [permissions.IsAuthenticated()]

In the above code, we are checking of the action (assuming you want to allow anyone to see the list, and limit who can perform other actions).

So if the action is list (HTTP method GET) it will allow anyone to access otherwise it will check for authentication.

Hope this answers your question.

Related