How to display data from API JSON for Django

32 Views Asked by At

I'm trying to create a weather website in Django but I don't know exactly how to get APIs data and display it in my templates.

Following a tutorial I arrived at this view:

from django.shortcuts import render
from django.http import HttpResponse
import requests

def weatherdata(request):
    response = requests.get('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,relative_humidity_2m,precipitation').json()
    context = {'response':response}
    return render(request,'home.html',context)

and this html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <strong>LATITUDE AND LONGITUDE</strong>
    {{latitude}} {{longitude}}
    </body>
</html>

considering the following lines in the API:

{"latitude":52.52,"longitude":13.419998,

and the result was, basically nothing. No error but no information was printed in the screen.

How do I solve this?

1

There are 1 best solutions below

0
Milos Stojanovic On

It seems like you are trying to display latitude and longitude in your HTML template, but you haven't passed those values to the context in your view. You need to extract the latitude and longitude from the API response and pass them to the context.

Here's how you can modify your view to include latitude and longitude in the context:

from django.shortcuts import render
import requests

def weatherdata(request):
    response = requests.get('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=temperature_2m,relative_humidity_2m,precipitation').json()
    latitude = response.get('latitude')
    longitude = response.get('longitude')
    context = {'latitude': latitude, 'longitude': longitude}
    return render(request, 'home.html', context)

Or, as you started by passing whole response, you can just get longitude and latitude directly in HTML template like this:

{{ response.latitude }} {{ response.longitude }}