4

I'm using Django Rest Framework's Generics (generics.ListCreateAPIView), when I make a POST request I get a response of Http code (200/400/..etc.) and a JSON showing the posted data, I need to know how can I override the response to get a custom response.

Note that I use

    def perform_create(self,serializer):
        return Response(<my response>)

to override the POST request handling but I still get the same response

P. Naoum
  • 457
  • 5
  • 14

1 Answers1

5

The response from perform_create is ignored. You'll likely want to override the create method using the mixins as example

Linovia
  • 19,812
  • 4
  • 47
  • 48
  • Should I use Mixins instead of generics, or is there a way to use both together ? – P. Naoum Jun 20 '17 at 14:50
  • Not sure what you mean but the idea is that you copy/paste the linked create method in your code, use the serializer.data as a base to build your own response data and finally pass them to the response. If you need to make that to several views you should definitively consider a Mixin that you'll add to your views. – Linovia Jun 20 '17 at 15:46
  • Working, Thank you! – P. Naoum Jun 20 '17 at 20:08
  • The problem with this is that if you override create instead of perform_create you need to (usually) copy a lot of the code in the normal create() in DRF. As DRF evolves, this might change and every piece of code you had to take from DRF into your overrides will eventually rot unless maintained. While you can't return custom responses directly from perform_create, you can derive your own APIExceptions and raise them there, and let the default APIView relay their custom contents to the client. – BjornW Nov 04 '20 at 15:00
  • "As DRF evolves, this might change" quite unlikely. Python 2 migration appart, most of the code is 6 years old and some part have been optimised 4 years ago (though you'll optimise better by yourself anyway). That's stable enough. – Linovia Nov 04 '20 at 17:29