django-rest-framework limit the allowed_methods to GET

If you are using ModelViewSet and still want to restrict some methods you can add http_method_names.

Example:

class SomeModelViewSet(viewsets.ModelViewSet):
    queryset = SomeModel.objects.all()
    serializer_class = SomeModelSerializer
    http_method_names = ['get', 'post', 'head']

Once you do this, get, post and head will be allowed. But put, patch and delete will not be allowed.


Sorry for necro, but I stumbled upon this question looking for a similar issue.

I only wanted to allow retrieve() but not to list(). What I ended up doing:

from rest_framework import viewsets
from rest_framework.exceptions import MethodNotAllowed

from myapp.models import MyModel

class MyViewSet(viewsets.ModelViewSet):
    http_method_names = ["get"]
    queryset = MyModel.objects.all()
    serializer_class = MySerializer

    def list(self, request, *args, **kwargs):
        raise MethodNotAllowed("GET")

As almost everything in django-rest-framework, once you find it out, its very simple. In the urls in stead of using ListOrCreateModelView I had to use ListModelView.