如何显示django api json中的数据

问题描述 投票:0回答:1

我正在尝试在 django 中创建一个天气网站,但我不知道如何获取 api 数据并将其显示在我的模板中。

按照教程,我得到了这个视图:

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)

还有这个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>

考虑 api 中的以下几行:

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

结果基本上什么也没有。没有错误,但屏幕上没有打印任何信息

我该如何解决这个问题?

django api django-views django-templates
1个回答
0
投票

您似乎正在尝试在 HTML 模板中显示纬度和经度,但您尚未将这些值传递到视图中的上下文。您需要从 API 响应中提取纬度和经度并将其传递给上下文。

以下是如何修改视图以在上下文中包含纬度和经度:

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)
© www.soinside.com 2019 - 2024. All rights reserved.