ViewSets are used to handle HTTP requests in the Django framework. Sometimes, we may need to disable certain HTTP methods like POST, PUT, DELETE, etc for specific ViewSets to restrict access or functionality. In this article, we will see how to disable a method in a ViewSet.

Using the ViewSets, we can handle multiple HTTP methods with a single class. This will reduce the unnecessary code and provides a clean way to define API endpoints

Disable a specific HTTP method in ViewSet?

To disable specific HTTP methods in a ViewSet, we can override the corresponding methods and raise the MethodNotAllowed exception. See the following example for more understanding of this.

from rest_framework import viewsets
from rest_framework.exceptions import MethodNotAllowed
from .models import MyModel
from .serializers import MyModelSerializer

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    def create(self, request, *args, **kwargs):
        raise MethodNotAllowed('POST')

In the above example, If the user sent any POST request to the MyModelViewSet it will return the 405 Method Not Allowed response.

Similarly, we can also disable multiple methods by overriding each of them separately as shown in the following example.

from rest_framework import viewsets
from rest_framework.exceptions import MethodNotAllowed
from .models import MyModel
from .serializers import MyModelSerializer

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    def create(self, request, *args, **kwargs):
        raise MethodNotAllowed('POST')

    def destroy(self, request, *args, **kwargs):
        raise MethodNotAllowed('DELETE')

Categorized in:

Tagged in: