我已经尝试了很多方法来解决这个问题,但每次我都遇到同样的问题。main上的city_weather中的键错误
import requests
from django.shortcuts import render
from .models import City
from .forms import CityForm
# Create your views here.
def weather(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=f5f13c3f6d997b396795738b674115cc'
city = 'Delhi'
if request.method == 'POST':
form = CityForm(request.POST)
form.save()
form = CityForm()
cities = City.objects.all()
weather_data = []
for city in cities:
r = requests.get(url.format(city)).json()
#print(r.text)
city_weather = {
'city': city.name,
'temperature': r['main']['temp'],
'description': r['weather'][0]['description'],
'icon': r['weather'][0]['icon']
weather_data.append(city_weather)
print(weather_data)
#print(city_weather)
context = {'weather_data': weather_data, 'form': form}
return render(request, 'weather.html', context)
我预计不会出现错误,但我得到了‘温度’:r 'main‘,KeyError:’main‘
发布于 2022-01-29 02:35:18
您需要转到管理页面并删除您之前创建的城市,因为您定义了未定义的城市名称,因此会收到一个错误。
发布于 2019-07-19 09:33:56
city_weather = {
'city': city.name,
'temperature': r['main']['temp'],
'description': r['weather'][0]['description'],
'icon': r['weather'][0]['icon']
} #you need to close the dictionary here
weather_data.append(city_weather)
发布于 2019-07-19 09:47:23
每当您看到KeyError时,其语义含义就是找不到正在查找的键。只需包含字典"city_weather“的右花括号(‘}’
https://stackoverflow.com/questions/57099942
复制