[Solved]-Django Rest Framework DELETE returns no content in the body

10👍

Sure thing. In your view, you’ll have to override destroy. Default implementation -by the time of writing this answer- is:

def destroy(self, request, *args, **kwargs):
    instance = self.get_object()
    self.perform_destroy(instance)
    return Response(status=status.HTTP_204_NO_CONTENT)

14👍

Complementing @Linovia’s otherwise complete answer with actionable code.

In the ViewSet, adding the following will help

class WhateverYourModelIsViewSet(viewsets.ModelViewSet):
    def destroy(self, *args, **kwargs):
        serializer = self.get_serializer(self.get_object())
        super().destroy(*args, **kwargs)
        return response.Response(serializer.data, status=status.HTTP_200_OK)

Few things to be aware of:

  • Returning 204 code will actually drop the data, you have to return something else
  • You need to extract the data from the serializer before you call destroy

Edit:

Since I first posted my answer, I found myself in need to do the above quite often. A more scalable solution:

class DestroyWithPayloadMixin(object):
     def destroy(self, *args, **kwargs):
         serializer = self.get_serializer(self.get_object())
         super().destroy(*args, **kwargs)
         return response.Response(serializer.data, status=status.HTTP_200_OK)

class WhateverYourModelIsViewSet(DestroyWithPayloadMixin, viewsets.ModelViewSet):
   # Your implementation 
   pass

Leave a comment