У меня есть keyerror: 'main'.Я искал много сайтов, но все еще не могу найти удовлетворительный ответ, чтобы решить эту ошибку.Я был бы очень признателен, если бы кто-нибудь дал мне несколько советов.Заранее спасибо.
Я попытался решить эту проблему, добавив в init .py функцию, предложенную сайтом.Но это все равно не сработало.https://forum.inductiveautomation.com/t/error-on-sys-modules/6431/2
код: view.py
from django.shortcuts import render
import requests
from .models import City
def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=MYKey'
cities = City.objects.all() # return all the cities in the database
city = 'Dhaka'
# request the API data and convert the JSON to Python data types
city_weather = requests.get(url.format(city)).json()
weather_data = []
for city in cities:
# request the API data and convert the JSON to Python data types
city_weather = requests.get(url.format(city)).json()
weather_app = {
'city': city,
'temperature': city_weather['main']['temp'],
'description': city_weather['weather'][0]['description'],
'icon': city_weather['weather'][0]['icon']
}
# add the data for the current city into our list
weather_data.append(weather_app)
#context = {'weather' : weather_app}
context = {'weather_data': weather_data}
# returns the index.html template
return render(request, 'weather_app/index.html')
терминал:
(env) acer@acer-Aspire-V3-472P:~/DjangoProject/Weather$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
May 03, 2019 - 06:48:01
Django version 2.2, using settings 'Weather.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /
Traceback (most recent call last):
File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/acer/DjangoProject/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/acer/DjangoProject/Weather/weather_app/views.py", line 30, in index
'temperature': city_weather['main']['temp'],
KeyError: 'main'
[03/May/2019 06:48:18] "GET / HTTP/1.1" 500 68977