DRF's not calling post() method when receiving POST request

124 Views Asked by At

I have a viewset like this:

class MyViewSet(CreateAPIView, RetrieveModelMixin, ListModelMixin, GenericViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MySerializer

    def post(self, request, *args, **kwargs):
        import pdb; pdb.set_trace()

class MySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = MyModel
        fields = ['id', 'field1', 'field2'] #only field1 is required in the model

The GET requests for list, and retrieve works perfectly. When I make a POST request, sending the field1 I get a status 201 and a new record is added to the database, so it works too.

But my method MyViewSet.post() that should overwrite the same one from generics.CreateAPIView never gets called.

Not only that, but I've tried to add the pdb.set_trace(), literally inside the generics.CreateAPIView.post() and in the CreateModelMixin.create() functions and neither stopped once I made the POST request.

So something else is handling this POST request and inserting into the DB, I just don't know what. And how can I overwrite it, so I can customize what should be done with a post request?

PS.: Also, I don't think it's a routing problem, my urls.py:

from rest_framework import routers
from myapp.views import MyViewSet, AnotherViewSet

router = routers.DefaultRouter()
router.register(r'route_one', MyViewSet)
router.register(r'route_two', AnotherViewSet)
1

There are 1 best solutions below

3
Metalgear On

I think you need to use the exact class in order to use POST api.

class MyView(CreateModelMixin, ListModelMixin, generics.GenericAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MySerializer

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

In urls.py

from django.urls import path
from .views import MyView

urlpatterns = [
    path('route_one', MyView.as_view(), name="my_view_detail")   
]