How to programmatically call a Django Rest Framewo

2019-01-22 06:40发布

I have the following generic class based views built with Django Rest framework (DRF)

class ExampleDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Example.objects.all()
    serializer_class = ExampleSerializer
    renderer_classes = (JSONRenderer, TemplateHTMLRenderer)

    def get(self, request, *args, **kwargs):

        response = self.retrieve(request, *args, **kwargs)
        if request.accepted_renderer.format == 'html':
            form = ExampleForm(data=response.data)
            return Response({'data': response.data, 'form': form}, template_name='example.html')

        return response

This view allow me to obtain both JSON data or HTML form from the same endpoint by specifying the format=json or html.

I would like to programmatically call that view to obtain the rendered HTML form from within another view in order to include this form in another page that will include more stuff.

3条回答
地球回转人心会变
2楼-- · 2019-01-22 06:51
html_from_view = ExampleDetail.as_view({'get': 'list'})(request).content

OR

html_from_view = ExampleDetail.as_view({'get': 'retrieve'})(request, pk=my_id).render().content
查看更多
We Are One
3楼-- · 2019-01-22 06:56

I found the solution for this in the documentation... https://docs.djangoproject.com/en/1.7/topics/class-based-views/mixins/

Hint is from their example here:

class AuthorDetail(View):

    def get(self, request, *args, **kwargs):
        view = AuthorDisplay.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = AuthorInterest.as_view()
        return view(request, *args, **kwargs)
查看更多
我命由我不由天
4楼-- · 2019-01-22 07:07

If I'm understanding correctly, you need to get the result from view B, while inside view A.

Using the requests/urllib2 and json libraries should solve your problem (as specified in this answer).

To get the URL, you can use a combination of request.get_absolute_uri() and/or request.get_host() and django.core.urlresolvers.reverse.

查看更多
登录 后发表回答