这是我的代码:
import requests
from django.shortcuts import render
from .models import City
def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=bd5e378503939ddaee76f12ad7a97608'
city = 'Jaipur'
cities = City.objects.all()
weather_data = []
for city in cities:
r = requests.get(url.format(city)).json()
city_weather = {
'city' : city.name,
'temperature' : r['main']['temp'],
'description' : r['weather'][0]['description'],
'icon' : r['weather'][0]['icon'],
}
weather_data.append(city_weather)
context = {'weather_data': city_weather}
return render(request, 'weather/weather.html', context)
我遇到这样的错误:
KeyError at /
'main'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.0.6
Exception Type: KeyError
Exception Value:
'main'
Exception Location: C:\Users\HP\p\the_waether\weather\views.py in index, line 18
Python Executable: C:\Users\HP\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.5
可能是什么问题?
答案 0 :(得分:0)
我也遇到这个错误。错误是我的API密钥错误。
因此,您进入for API key link并注册,然后select free plan然后单击get API并检查您的电子邮件。在网址中插入API密钥。
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=YOUR_API_KEY'
就这样
答案 1 :(得分:0)
您只需在本节中删除一些代码即可对代码进行更改:
for city in cities:
city_weather = {
'city' : city.name,
'temperature' : temp,
'description' : description,
'icon' : icon,
}
答案 2 :(得分:0)
您的代码没有问题,但是我遇到了同样的问题,但是问题是当您输入一个在openweatherapp数据库中不存在的城市时,它给您一个错误,因为它找不到它的天气数据,因此您需要要做的是添加尝试,除了那样,错误消失了
别忘了输入您的应用ID
代码:-
def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=c12a48c9ac1ec37bedd3cc51b1af4e8b'
if request.method == 'POST':
form = CityForm(request.POST)
form.save()
form = CityForm()
cities = City.objects.all()
weather_data = []
try:
for city in cities:
r = requests.get(url.format(city)).json()
city_weather = {
'city' : city.name,
'temperature' : r['main']['temp'],
'description' : r['weather'][0]['description'],
'icon' : r['weather'][0]['icon'],
}
weather_data.append(city_weather)
except KeyError:
pass
except EXCEPTION as e:
pass
context = {'weather_data' : weather_data, 'form' : form}
return render(request, 'weather/weather.html', context)
答案 3 :(得分:0)
您遇到此错误是因为您在“添加城市”框中输入了一些随机单词,而不是城市名称。转到管理面板,转到城市,然后删除除城市名称以外的随机单词。 (管理员>天气>城市)
答案 4 :(得分:-1)
您的models.py文件中肯定有错误
更改此内容
def
_str_
(self):
#some code
收件人
_str_