0

I want to post to an endpoint from within a CBV and retrieve the response (in order to access the id of the created resource). I've had a look at How to programmatically call a Django Rest Framework view within another view? but cannot find how to send field values through with the request object. request.data is immutable, and passing kwargs through doesn't seem to be doing anything:

from app.views import OtherViewSet

class NewViews(APIView):
   def post(self, request, *args, **kwargs):
       # kwargs value here is {'field1':1, 'field2':2...}
       view_func = OtherViewSet({'post':'create'})
       response = view_func(self.request, *args, **kwargs).data

Although the kwargs contains the field values (set through several url named groups), the response always looks like:

{'field1': ['This field is required'], 'field2':['This field is required...

What am I doing wrong? Thanks all :)

Edit: Once I've got the ID of the created resource, I want to retrieve the resource as rendered by a particular (custom) format (I don't want to return the response object above).

Liz
  • 1,421
  • 5
  • 21
  • 39
  • Why not use a specific serializer, that may reuse the serializer from `OtherViewSet` ??? – Gabriel Muj Nov 16 '17 at 10:52
  • @GabrielMuj can you give an example here? I'm not sure how this would look - I need to access the data after making a request to the OtherViewSet's create endpoint within this view. – Liz Nov 16 '17 at 23:51
  • Can you provide the serializer from `OtherViewSet` and what data you need in `NewView`? – Gabriel Muj Nov 18 '17 at 12:51
  • I could do, but it doesn't seem particularly DRY. I also want to return the result in a particular format so need to render the response via one of our custom renderers. – Liz Nov 19 '17 at 23:02
  • I was thinking that maybe you can reuse the serializer from `Otherviewset` by subclass it. – Gabriel Muj Nov 20 '17 at 07:37

1 Answers1

0

views.py

from app.views import OtherViewSet

class NewViews(APIView):
    def post(self, request, *args, **kwargs):
        view = OtherViewSet.as_view({'post':'create'})
        response = view(request, *args, **kwargs)
        return response
origamic
  • 1,076
  • 8
  • 18
  • I get: django.http.request.RawPostDataException: You cannot access body after reading from request's data stream. However, I need to access the data from the response, not return it. – Liz Nov 16 '17 at 23:47