Home > OS >  How to render two views into one template using Django
How to render two views into one template using Django

Time:12-17

fair to mention I'm just starting out with learning Django, and I could really use the help.

To paint a clear picture, there are two API endpoints that I have to use and each one of them has to be rendered in the same template (HTML file) meaning they have to be in the same URL path as well, but I couldn't figure it out yet, I tried with both the function and class-based views but I got nowhere.

views.py:

class HomePage(TemplateView):
    template_name = 'home.html'

    def home(self, request):
        response = requests.get('https://api.covid19api.com/world/total').json()
        print('res',response.data)
        return render(request, 'home.html', {'response': response})


    def other(self, request):
        response= requests.get('https://api.covid19api.com/country/south-africa/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json()
        return render(request, 'home.html', {'response': response})

urls.py:

urlpatterns = [
    path('home', HomePage.as_view(), name='home')
]

home.html:

{% extends '_base.html' %}

{% block page_title %} Covid19 Statistics {% endblock %}


{% block content %}

<br>

<br>

<h3 >World Total Statistics </h3>

<br>

<!-- <div >
    <div >


        <div >
            <div  style="max-width: 20rem;">
                <div >
                    <h5 >Total Confirmed: {{response.TotalConfirmed}}</h5>
                </div>
            </div>
        </div>

        <div >
            <div  style="max-width: 20rem;">
                <div >
                    <h5 >Total Deaths: {{response.TotalDeaths}}</h5>
                </div>
            </div>
        </div>

        <div >
            <div  style="max-width: 20rem;">
                <div >
                    <h5 >Total Recovered: {{response.TotalRecovered}}</h5>
                </div>
            </div>
        </div>
    </div>
</div>
 -->

<br><br>

<h4 >Get Statistics For a Specific Country </h4>

{% for object in response %}

<div  style="width: 35rem;">
    <h3 ></h3>
    <div >
      <p >{{object.Country}} </p>
      <p >{{object.Date}} </p>
    </div>
  </div>

{% endfor %}

{% endblock%}

Any help is appreciated, thank you in advance

CodePudding user response:

You can call two api in one view as:

 def home(self, request):
    first_response = requests.get('https://api.covid19api.com/world/total').json()
    second_response = requests.get('https://api.covid19api.com/country/south-africa/status/confirmed?from=2020-09-06T00:00:00Z&to=2020-09-11T00:00:00Z').json()
   
    return render(request, 'home.html', {'first_response ': first_response ,'second_response':second_response })
  • Related