Site icon StudyGyaan

Build a Weather App in Python Django: Guide with Example

Django Web Framework Tutorials

Weather apps are a popular and practical application of web development. In this tutorial, we’ll guide you through the process of creating a weather app in Django. You’ll learn how to retrieve weather data from a weather API, display it in a user-friendly interface, and provide real-time weather information to your users. By the end of this tutorial, you’ll have a functional weather app that can be expanded and customized to suit your specific needs.

Prerequisites

Before we begin, make sure you have the following prerequisites:

  1. Python and Django installed on your system.
  2. Access to a weather API. For this tutorial, we’ll use the OpenWeatherMap API. You can sign up for a free API key at OpenWeatherMap.

Implement Weather App using OpenWeatherMap API in Python Django

Step 1: Create a Django Project and App

Start by creating a new Django project and app:

django-admin startproject weather_project
cd weather_project
python manage.py startapp weather_app

Step 2: Configure Django Settings

In your project’s settings.py, add the weather_app to the INSTALLED_APPS list:

INSTALLED_APPS = [
    # ...
    'weather_app',
]

Step 3: Create a Weather Form

In weather_app/forms.py, create a form to collect user input (i.e., the city for which they want to retrieve weather information):

from django import forms

class WeatherForm(forms.Form):
    city = forms.CharField(max_length=50, label='Enter a city')

Step 4: Create a Weather View

In weather_app/views.py, create a view to handle the form submission, retrieve weather data from the API, and display it in the template:

import requests
from django.shortcuts import render
from .forms import WeatherForm

def get_weather_data(city):
    api_key = 'YOUR_API_KEY'  # Replace with your OpenWeatherMap API key
    base_url = 'http://api.openweathermap.org/data/2.5/weather'
    params = {'q': city, 'appid': api_key, 'units': 'metric'}
    response = requests.get(base_url, params=params)
    data = response.json()
    return data

def weather(request):
    if request.method == 'POST':
        form = WeatherForm(request.POST)
        if form.is_valid():
            city = form.cleaned_data['city']
            weather_data = get_weather_data(city)

            if weather_data['cod'] == 200:
                temperature = weather_data['main']['temp']
                description = weather_data['weather'][0]['description']
                context = {'temperature': temperature, 'description': description, 'city': city}
            else:
                context = {'error_message': 'City not found'}

            return render(request, 'weather_app/weather.html', context)
    else:
        form = WeatherForm()

    return render(request, 'weather_app/weather.html', {'form': form})

Step 5: Create a Template

Create a template in the weather_app/templates/weather_app directory to display the weather information (weather.html):

<!DOCTYPE html>
<html>
<head>
    <title>Weather App</title>
</head>
<body>
    <h1>Weather App</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Get Weather</button>
    </form>
    {% if temperature %}
    <h2>Weather in {{ city }}</h2>
    <p>Temperature: {{ temperature }}°C</p>
    <p>Description: {{ description }}</p>
    {% elif error_message %}
    <p>{{ error_message }}</p>
    {% endif %}
</body>
</html>

Step 6: Configure URLs

Configure the URL routing for your app by adding URL patterns in weather_app/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('weather/', views.weather, name='weather'),
]

Include the app’s URLs in your project’s urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('weather_app.urls')),
]

Step 7: Run the Development Server

Run the Django development server:

python manage.py runserver

Visit http://127.0.0.1:8000/weather/ in your browser. You’ll see a form where you can enter a city. Upon submission, the page will display the current weather temperature and description for the specified city

Conclusion

In this tutorial, you learned how to create a weather app in Django. You’ve integrated the OpenWeatherMap API to fetch weather data, displayed it on a web page, and allowed users to input a city to get real-time weather information. This project serves as foundation that you can build upon to create more feature-rich weather appps, including forecasts, location-based weather, and more.

Blogs You Might Like to Read!
Exit mobile version