Weather App Using Django
×


Weather App Using Django

545

Introduction to Building a Weather App Using Django

Building a Weather App Using Django is an excellent way to explore API integration, form handling, and template rendering in a real web application. By tapping into APIs like OpenWeatherMap, you can create an interactive app that responds to user city input and displays current weather details.

Project Overview

The app allows users to input a city name, fetch its current weather data via an external API, then render temperature, humidity, and conditions dynamically. This project emphasizes Django forms, views, URL routing, and template design.

Step 1: Project & App Setup

django-admin startproject weather_project
cd weather_project
python manage.py startapp weather_app
# Add 'weather_app' to INSTALLED_APPS in settings.py

Step 2: Create the Input Form

from django import forms

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

This simple form captures the city whose weather you'd like to see :contentReference[oaicite:0]{index=0}.

Step 3: View Logic & API Integration

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

def weather_view(request):
    weather_data = {}
    if request.method == 'POST':
        form = WeatherForm(request.POST)
        if form.is_valid():
            city = form.cleaned_data['city']
            url = 'http://api.openweathermap.org/data/2.5/weather'
            params = {'q': city, 'appid': 'YOUR_API_KEY', 'units': 'metric'}
            resp = requests.get(url, params=params)
            if resp.status_code == 200:
                weather_data = resp.json()
            else:
                weather_data['error'] = 'City not found'
    else:
        form = WeatherForm()
    return render(request, 'weather_app/weather.html', {'form': form, 'weather_data': weather_data})

This view sends a request to the OpenWeatherMap API and processes the JSON response :contentReference[oaicite:1]{index=1}.

Step 4: Template Rendering

<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Get Weather</button>
</form>

{% if weather_data.main %}
  <h2>Weather in {{ form.cleaned_data.city }}</h2>
  <p>Temperature: {{ weather_data.main.temp }}°C</p>
  <p>Humidity: {{ weather_data.main.humidity }}%</p>
  <p>Condition: {{ weather_data.weather.0.description }}</p>
{% elif weather_data.error %}
  <p>{{ weather_data.error }}</p>
{% endif %}

Step 5: URL Configuration

from django.urls import path
from .views import weather_view

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

Enhancements & Tips

  • Allow GET requests for bookmarking and sharing links.
  • Add a default city display (e.g., London) for initial load :contentReference[oaicite:2]{index=2}.
  • Display icons based on weather conditions using the API’s icon codes :contentReference[oaicite:3]{index=3}.
  • Implement auto-refresh via JavaScript or meta refresh tags.
  • Handle errors gracefully and inform users of invalid inputs.

Conclusion

This Weather App Using Django combines API requests, form handling, and dynamic templates to create a functional, real-world application. It serves as a strong foundation for developers to build more advanced features like multi-day forecasts, location storage, or interactive maps.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Unlimited Video Generation

Best Platform to generate videos

Search and buy from Namecheap

Secure Domain for a Minimum Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat