ViewSets
have automatic methods to list, retrieve, create, update, delete, ...
I would like to disable some of those, and the solution I came up with is probably not a good one, since OPTIONS
still states those as allowed.
Any idea on how to do this the right way?
class SampleViewSet(viewsets.ModelViewSet):
queryset = api_models.Sample.objects.all()
serializer_class = api_serializers.SampleSerializer
def list(self, request):
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
def create(self, request):
return Response(status=status.HTTP_405_METHOD_NOT_ALLOWED)
How to disable "DELETE" method for ViewSet in DRF
P.S. This is more reliable than explicitly specifying all the necessary methods, so there is less chance of forgetting some of important methods OPTIONS, HEAD, etc
P.P.S. by default DRF has
http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
If you are trying to disable the PUT method from a DRF viewset, you can create a custom router:
By disabling the method at the router, your api schema documentation will be correct.
The definition of
ModelViewSet
is:So rather than extending
ModelViewSet
, why not just use whatever you need? So for example:With this approach, the router should only generate routes for the included methods.
Reference:
ModelViewSet
You could keep using
viewsets.ModelViewSet
and definehttp_method_names
on your ViewSet.Example
Once you add
http_method_names
, you will not be able to doput
andpatch
anymore.If you want
put
but don't wantpatch
, you can keephttp_method_names = ['get', 'post', 'head', 'put']
Internally, DRF Views extend from Django CBV. Django CBV has an attribute called http_method_names. So you can use http_method_names with DRF views too.