Control ViewSet Method in Django

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.

Advert

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.

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. User Account Details in Django Extended UserModel Serializer

     
  2. Configure and Deploy Django Project on VPS

     
  3. World Wide Web at end of 2016

     
  4. 6 Essential Practices for Ecommerce Blog

     
  5. Text Area Widget in Django Admin

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.