**我正在django中创建一个天气应用程序,我希望用户能够在任何天气条件下搜索天气 使用API的位置...我已经尝试过多次使用HTML输入,但无法正常工作
def home(请求):
choose_city = "London" #selected city
url = f"https://openweathermap.org/data/2.5/weather?q=
{choose_city}&units=imperial&appid=b6907d289e10d714a6e88b30761fae22" #open weather url
response = requests.get(url)
get_weather = response.json()
for weather in get_weather["weather"]:
pass
temperature = get_weather["main"]
city_name = get_weather["name"]
weatherContext = {
"main" : weather["main"],
"description": weather["description"],
"temp": temperature,
"city_name": city_name,
"city": choose_city,
"url": url
}
return render(request, "MyWeather/base.html", weatherContext)
here is the HTML
Blockquote
<div class="wrapper">
<div class="container">
<nav class="navbar navbar-light bg-light" id="nav">
<form class="form-inline" action={{url}}>
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" >
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search </button>
</form>
</nav>
<br>
<div>
<h2>
City: {{city_name}}
</h2>
</div><br><br>
<h4>Weather: {{main}}</h4><br><hr>
<h4> Description: {{description}}</h4><br><hr>
{% for temperature, key in temp.items%}
{%if temperature == "temp"%}
<h4>Temperature: {{key}} °F</h4><br><hr>
{%endif%}
{%endfor%}
我该如何解决此问题
答案 0 :(得分:0)
这是您的代码中的问题:
for weather in get_weather["weather"]:
pass
它实际上什么也没做。 在尝试api时,有一个天气列表。因此您可以尝试“天气”的第一个元素
weather = get_weather["weather"][0] #it will get the first element always
如果变量中没有元素,则上面的代码会引发错误。 因此,请尽量避免出现任何错误:
if get_weather["weather"]: # if found any data
weather = get_weather["weather"][0]
else:
weather = {}