0

I was building a simple weather app with Django. This app allows the user to enter a city name and it will give the weather details of that city. I am using an API to fetch the data.

I wanted to avoid KeyError when an user enters an empty string or misspelled a city. I kinda achieved my goal, but I wonder if there is a much easier way to do this.

Here is my code:

from django.shortcuts import render
import requests
from datetime import datetime
import geonamescache  # Used for match checking


def home(request):

    # Checks for legitimate cities
    if 'search-city' in request.POST:
        gc = geonamescache.GeonamesCache()
        while request.POST['search-city'] != '':
            cities = str(gc.get_cities_by_name(request.POST['search-city']))
            if request.POST['search-city'] in cities:
                city = request.POST['search-city']
                break
            elif request.POST['search-city'] not in cities:
                city = 'Amsterdam'
                break

        while request.POST['search-city'] == '':
            city = 'Amsterdam'
            break

    # Call current weather
    URL = 'https://api.openweathermap.org/data/2.5/weather'
    API_KEY = 'MY_KEY'
    PAR = {

        'q': city,
        'appid': API_KEY,
        'units': 'metric'
    }

    req = requests.get(url=URL, params=PAR)
    res = req.json()

    city = res['name']
    description = res['weather'][0]['description']
    temp = res['main']['temp']
    icon = res['weather'][0]['icon']
    country = res['sys']['country']
    day = datetime.now().strftime("%d/%m/%Y %H:%M")

    weather_data = {

        'description': description,
        'temp': temp,
        'icon': icon,
        'day': day,
        'country': country,
        'city': city
    }

    return render(request, 'weatherapp/home.html', weather_data)

Could you guys show me how you would do this? Thanks!

2
  • 1
    You can use .get() method Commented Jun 10, 2022 at 12:40
  • you may also want to implement fuzzy matching when the city is not found. There's a couple of libraries that can make this easy for you to implement, and easy for your users if they are prone to fat-finger errors Commented Jun 10, 2022 at 12:43

1 Answer 1

1

I have not personally used this, but Django and other frameworks provide a way to do something called "Form Validation." https://docs.djangoproject.com/en/4.0/ref/forms/validation/, but this would require a few more things to be in place like a class that models what your form looks like too: https://docs.djangoproject.com/en/4.0/topics/forms/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.