DEV Community

Cover image for Building a Real-Time Weather Dashboard with OpenWeather API and Django
kihuni
kihuni

Posted on

Building a Real-Time Weather Dashboard with OpenWeather API and Django

Weather impacts our daily lives, whether we’re planning outdoor activities, avoiding unexpected storms, or staying ahead of extreme conditions. The OpenWeather API provides real-time weather data, including temperature, humidity, wind speed, and forecasts, making it a powerful tool for developers building weather-related applications.

In this guide, we’ll build a real-time weather dashboard using Django and the OpenWeather API. You will learn how to fetch live weather data, display it dynamically, and refresh it automatically for up-to-date insights. Whether you’re looking to sharpen your Django skills or create a practical tool, this hands-on tutorial will guide you step by step.

What You'll Learn:

  • How to set up a Django project and fetch live data from OpenWeather API
  • How to display weather updates dynamically in a clean, structured UI
  • How to auto-refresh your dashboard every few minutes
  • Best practices for handling API responses

By the end, you’ll have a functional weather dashboard that refreshes in real time—something you can proudly add to your portfolio.

Prerequisites

Before you begin, ensure you have::

  • Basic understanding of Python programming
  • Basic knowledge of the Django framework
  • Python 3.x installed Download here
  • An OpenWeather API key Sign up for free
  • Experience using the command-line interface
  • Basic knowledge of HTML & CSS (optional, but helps with styling)

Got all that? Let’s get started.

Step 1: Set Up Your Development Environment

First, create a new project folder and set up a virtual environment:

# Create a project folder
mkdir weather-dashboard && cd weather-dashboard

# Create a virtual environment
python -m venv venv

# Activate the virtual environment (Windows)
venv\Scripts\activate

# Activate the virtual environment (Mac/Linux)
source venv/bin/activate

# Install Django
pip install django

Enter fullscreen mode Exit fullscreen mode

Step 2: Create a Django Project and App

Now, let's create a Django project and an app to manage our weather dashboard.

# Create a Django project
django-admin startproject weather_dashboard

cd weather_dashboard

# Create a Django app
python manage.py startapp weather
Enter fullscreen mode Exit fullscreen mode

Tell Django about our new app by adding 'weather' to INSTALLED_APPS in weather_dashboard/settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'weather' # Add this
]
Enter fullscreen mode Exit fullscreen mode

Test your setup by running:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Visit localhost:8000 and you should see Django's welcome page.

Real-Time Weather Dashboard

Step 3: Fetch Weather Data with OpenWeather API

We'll use Python's requests library to fetch real-time weather data. First, install the package:

pip install requests
Enter fullscreen mode Exit fullscreen mode

Next, open weather/views.py and add the following code:

import requests
from django.shortcuts import render

def weather_dashboard(request):
    api_key = "ad6aecd89efa1c4c7ba9ff804afbc8cd"  # Replace with your OpenWeather API key
    city = request.GET.get('city', 'Nairobi')  # Get city from user input, default to Nairobi
    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"

    response = requests.get(url)
    data = response.json()

    if response.status_code == 200:
        context = {
            'city': city,
            'temp': data['main']['temp'],
            'humidity': data['main']['humidity'],
            'description': data['weather'][0]['description'],
        }
    else:
        context = {'error': 'City not found. Please try again.'}

    return render(request, 'weather/dashboard.html', context)
Enter fullscreen mode Exit fullscreen mode

Replace "your_api_key_here" with your actual API key. This code:

  • Calls the OpenWeather API for Nairobi’s weather.
  • Extracts temperature, humidity, and weather conditions.
  • Passes this data to a template for rendering.

Test your API call by printing data to the terminal:

print(data) // add this after `data = response.json()`
Enter fullscreen mode Exit fullscreen mode

Json data

Step 4: Create a Dashboard Template

Let’s create a simple HTML template to display our weather data.

First, create the templates directory:

mkdir -p weather/templates/weather
Enter fullscreen mode Exit fullscreen mode

Now, create dashboard.html inside weather/templates/weather/ and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Weather Dashboard</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
        .weather-box { border: 1px solid #ccc; padding: 20px; max-width: 300px; margin: 0 auto; }
        h1 { color: #333; }
        input, button { padding: 10px; margin-top: 10px; }
    </style>
</head>
<body>
    <h1>Weather Dashboard</h1>
    <form method="GET" action="">
        <input type="text" name="city" placeholder="Enter city name">
        <button type="submit">Search</button>
    </form>

    {% if error %}
    <p>{{ error }}</p>
    {% else %}
    <div class="weather-box">
        <h2>{{ city }} Weather</h2>
        <p>Temperature: {{ temp }}°C</p>
        <p>Humidity: {{ humidity }}%</p>
        <p>Condition: {{ description }}</p>
    </div>
    {% endif %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Step 5: Set Up URLs

Now, let's connect our view to a URL.

Edit weather_dashboard/urls.py to include our app::

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('weather.urls')),  # Include our weather app URLs
]
Enter fullscreen mode Exit fullscreen mode

Create weather/urls.py in your weather app:

from django.urls import path
from .views import weather_dashboard

urlpatterns = [
    path('', weather_dashboard, name='weather_dashboard'),
]
Enter fullscreen mode Exit fullscreen mode

Run the server again:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:8000/—you should see your dashboard with London’s weather!

weather data

Step 6: Add Auto-Refresh for Real-Time Updates

Let’s make it “real-time” by refreshing the data periodically. For a demo, a simple HTML trick works fine.

To refresh the weather data every 5 minutes, update dashboard.html and add this in the

<meta http-equiv="refresh" content="300"> <!-- Refresh every 5 minutes -->
:
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="refresh" content="300"> <!-- Refresh every 5 minutes -->
    <title>Weather Dashboard</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
        .weather-box { border: 1px solid #ccc; padding: 20px; max-width: 300px; margin: 0 auto; }
        h1 { color: #333; }
        input, button { padding: 10px; margin-top: 10px; }
    </style>
</head>
<body>
    <h1>Weather Dashboard</h1>
    <form method="GET" action="">
        <input type="text" name="city" placeholder="Enter city name">
        <button type="submit">Search</button>
    </form>

    {% if error %}
    <p>{{ error }}</p>
    {% else %}
    <div class="weather-box">
        <h2>{{ city }} Weather</h2>
        <p>Temperature: {{ temp }}°C</p>
        <p>Humidity: {{ humidity }}%</p>
        <p>Condition: {{ description }}</p>
    </div>
    {% endif %}
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

N/b In production, use Django Channels for WebSocket updates or Celery for scheduled API calls.

Conclusion

🎉 Congrats—you’ve built a real-time weather dashboard with Django and the OpenWeather API! Your app fetches live data and refreshes automatically.

👉 View the full project on GitHub

Keep building, keep experimenting, and happy coding! 🚀.

Top comments (0)