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)
The definition of ModelViewSet
is:
class ModelViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
mixins.ListModelMixin,
GenericViewSet)
So rather than extending ModelViewSet
, why not just use whatever you need? So for example:
from rest_framework import viewsets, mixins
class SampleViewSet(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet):
...
With this approach, the router should only generate routes for the included methods.
Reference:
@SunnySydeUp Just trying this now and it seems the router does generate the route for a list view, but it 404s because the ViewSet doesn't know how to handle the request. Is this what you expected?
By only using the mixins you need you can disable GET, POST, PUT, DELETE Methods but I did not able to find out how to disable the PATCH method specially if you are using routers.
@MuneebAhmad The PATCH method is enabled from the
UpdateModelMixin
. If you want to use update but not the patch, I can currently think of two ways. You can either override the allowed methods in the view and remove "patch" or you can override thepartial_update
method and callhttp_method_not_allowed(request, *args, **kwargs)
. I haven't tested this so I'm not sure if it works@JulioMarins I've added a reference. I'm not sure if this is what you wanted though.
If someone wants to make read-only viewset then they can use
class SampleViewSet(viewsets.ReadOnlyModelViewSet)
.