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).

5
  • Why not use a specific serializer, that may reuse the serializer from OtherViewSet ??? Commented Nov 16, 2017 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. Commented Nov 16, 2017 at 23:51
  • Can you provide the serializer from OtherViewSet and what data you need in NewView? Commented Nov 18, 2017 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. Commented Nov 19, 2017 at 23:02
  • I was thinking that maybe you can reuse the serializer from Otherviewset by subclass it. Commented Nov 20, 2017 at 7:37

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.