首页 > 解决方案 > 在 Django 中的 API URL 中传递参数

问题描述

我正在玩 API,这是我的第一个 API 视图,请帮助我理解我错在哪里。

我使用这个 API api.openweathermap.org/data/2.5/weather?q={city name},{country code} 我写了这个视图:

def forecast(request):
    url = 'http://api.openweathermap.org/data/2.5/weather?q= {}&appid=My_Key'

cities = {'city': 'London', 'cod' : 826} 


city_weather = requests.get(url.format(cities)).json()

weather = {
    'temperature': city_weather['main']['temp'],# one parameter, just to check whethe it works

}

context = {'weather' : weather }
return render(request, 'weather/forecast.html')

这是非常基本的视图,就像我的第一个 print("Hello, World!") ,但 id 根本不起作用))如果您建议我一些关于此的文章,我将不胜感激。在这里没有找到答案http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content

标签: apidjango-views

解决方案


您需要将保存的数据传递到视图中

context = {'weather' : weather }
return render(request, 'weather/forecast.html', context=context)

然后,您可以访问contexthmtl 脚本内的变量中的数据

<div>
{{ weather }}
</div>

推荐阅读