How to programmatically call a Django Rest Framework view within another view?

前端 未结 5 1373
醉酒成梦
醉酒成梦 2020-12-04 17:38

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

class ExampleDetail(generics.RetrieveUpdateDestroyAPIView):
    queryse         


        
相关标签:
5条回答
  • 2020-12-04 18:18

    As of Django 2.2 and DRF 3.9.2 I am able to get response using below code.

    response = UserItemsApiView.as_view()(request=request._request).data
    

    Above example solves below issues:

    • The request argument must be an instance of django.http.HttpRequest, not rest_framework.request.Request
    • Instead of content, using data attribute gave me result from that view.
    0 讨论(0)
  • 2020-12-04 18:19

    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)
    
    0 讨论(0)
  • 2020-12-04 18:21

    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.

    0 讨论(0)
  • 2020-12-04 18:22

    I didn't tried it, but I think the following should work.

    • Server side:

    Call the DRF and poing by url.open or request

    as this answer suggest

    Example:

    import requests
    from django.shortcuts import render
    
    
    def home(request):
       # get the list of todos
       response = 
        requests.get('https://jsonplaceholder.typicode.com/todos/')
       # transfor the response to json objects
       todos = response.json()
       return render(request, "main_app/home.html", {"todos": todos})
    

    Complete example

    • Client side:

    You can call the DRF and point by ajax request from any other view.

    0 讨论(0)
  • 2020-12-04 18:31
    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
    
    0 讨论(0)
提交回复
热议问题