Nitish Kumar
Nitish Kumar

Reputation: 39

Why is there the KeyError 'main' in my code?

I have tried a lot to resolve the problem but everytime I'm getting the same problem...i.e. key error in the city_weather at main

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)

I expected no errors but I'm getting the 'temperature': r['main']['temp'], KeyError: 'main'

Upvotes: 2

Views: 1522

Answers (3)

Yakup Kaynak
Yakup Kaynak

Reputation: 11

You need to go to the admin page and delete the cities you created before, because you are getting an error because you defined undefined city names.

Upvotes: 1

shubham
shubham

Reputation: 182

Whenever you see a KeyError , the semantic meaning is that the key being looked for could not be found. Just include the closing curly bracket ('}') for the dictionary "city_weather"

Upvotes: 0

AnkushRasgon
AnkushRasgon

Reputation: 820

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)

Upvotes: 0

Related Questions