Model ViewSets packs up the common functions to create, list, patch, put and delete an object in the package, which saves the day in many places but there are situations where you need to limit these functions for security reasons.

It’s possible to attack the problem in two ways :

  • Functionally limiting the Model ViewSet by using the required functions instead of inheriting everything.
  • Restrict the access methods (GET, POST, PUT, PATCH, DELETE).

Functional Limiting

ModelViewSet is composed of


class ModelViewSet(mixins.CreateModelMixin, 
  mixins.RetrieveModelMixin, 
  mixins.UpdateModelMixin,
  mixins.DestroyModelMixin,
  mixins.ListModelMixin,
  GenericViewSet):

replacing with a custom viewset as per need will server the functions.


class MyViewSet(mixins.CreateModelMixin,
  mixins.DestroyModelMixin,
  viewsets.GenericViewSet):

Method Names

If you don’t want to mess with the viewset you can use ModelViewSet and define http_method_names and restrict the access methods.


class MYViewSet(viewsets.ModelViewSet):
  queryset = myobject.objects.filter()
  serializer_class = mySerializer
  permission_classes = (permissions.IsAuthenticated,)
  http_method_names = ['post']

When using http_method_names you have to specify all method you need.