In this Tutorial, We will create Weather app in Django using OpenWeatherMap’s Weather API(Application Programming Interface). This API is free and fastest API from OpenWeatherMap. This API will give us the access of Weather Data.

Weather API’s free plan allow users up to 60 calls per minute.

For GitHub Repository Scroll Down.

Installation

First, We need to install and setup Django.

Then, We have to setup Weather API.

Setting up Weather API

First, we need to create account and sign in to OpenWeatherApps.

After sign in click on API keys. In API Keys you will see your own key. We will use that key to show weather details of specific location.

(NOTE:- PLEASE DO NOT SHARE YOUR API KEY TO ANYONE)

API Keys

Now we will Try to see details on Web Browser using your API Key.

Write URL in this Format :- https://api.openweathermap.org/data/2.5/weather?q=CITY_NAME&units=imperial&appid=PASTE_YOUR_API_KEY_HERE

(NOTE:- YOU HAVE TO EDIT BOLD TEXT FROM URL)

URL will show result like this :

{"coord":{"lon":55.3047,"lat":25.2582},"weather:[{"id":801,"main":"Clouds","description":"few clouds","icon":"02d"}],"base":"stations","main":{"temp":96.39,"feels_like":108.99,"temp_min":95.25,"temp_max":96.73,"pressure":998,"humidity":59},"visibility":10000,"wind":{"speed":9.22,"deg":220},"clouds":{"all":20},"dt":1657691191,"sys":{"type":1,"id":7537,"country":"AE","sunrise":1657676196,"sunset":1657725117},"timezone":14400,"id":292223,"name":"Dubai","cod":200}

Now we will link this API key with our Django Project.

Creating Weather App

After installing Django we will create urls.py in apps folder and edit urls.py inside project directory.

urls.py in project directory :

from django.contrib import admin
from django.urls import path
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('main/', views.main, name='main')
]

urls.py in apps folder :

from django.urls import path  
from .views import main  
urlpatterns = [  
    path('', main, name = 'main')  
]  

After editing urls.py migrate the project.

Write this command in terminal or command prompt to migrate :

python manage.py migrate

Now we will edit views.py in apps folder. In views.py we will connect and map API with Django.

views.py :

import json  
from django.shortcuts import render  
import urllib.request  
import json  

def main(request):  
    if request.method == 'POST': 
        city = request.POST.get('city', 'True')  
        source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=imperial&appid=PASTE_YOUR_API_KEY').read()  
        list_of_data = json.loads(source)  
        context = {  
            'city': city, 
            "pressure": str(list_of_data['main']['pressure']),  
            "humidity": str(list_of_data['main']['humidity']),   
            "country_code": str(list_of_data['sys']['country']),  
            "coordinate": str(list_of_data['coord']['lon']) + ' ' + str(list_of_data['coord']['lat']),  
            "temp": str(list_of_data['main']['temp']) + ' K',  
        }  
    else:  
        context = {}  
    return render(request, 'index.html', context)  

(NOTE :- DON’T FORGET TO PASTE YOUR API KEY)

After editing views.py, We will create an HTML file so we can show our details dynamically.

Create a ‘templates’ named folder in apps folder so we can put our HTML file in it.

Templates Folder

Now, Write this code in your HTML file.

index.html :

<!DOCTYPE html>
<html>
    <head>
        <title>Weather App</title>
        <style>
            *
            {
                font-family:'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
                background-color:rgb(159, 247, 253);
            }
        </style>
    </head>
    <body>
        <h1>Weather App</h1>
        <form method="post" class="col-md"">  
            {% csrf_token %}  
            <div class=" input-group">  
                <input type="text" class="form-control" name="city" placeholder="Choose Your City">  
                <div class="input-group-btn">  
                    <button type="submit" class="btn btn-primary">Search</button>  
                </div>  
            </div>  
        <form>
            <div>
                {% if country_code and coordinate and temp and pressure and humidity %}  
                <div>
                    <h4><span class="badge badge-primary">City :</span> {{city}}</h4>  
                    <h4><span class="badge badge-primary">Country Code :</span> {{country_code}}</h4>  
                    <h4><span class="badge badge-primary">Coordinates [X,Y] :</span> {{coordinate}}</h4>  
                    <h4><span class="badge badge-primary">Temperature :</span> {{temp}}</h4>  
                    <h4><span class="badge badge-primary">Pressure :</span> {{pressure}} </h4>  
                    <h4><span class="badge badge-primary">Humidity : </span> {{humidity}}</h4>  
                </div>
                {% endif %}  
            </div>
    </body>
</html>

Lastly, you have to simply run this project by using this command in terminal or command prompt :

python manage.py runserver

Write this URL for Output http://127.0.0.1:8000/main

Output :

Output of Weather App

For whole Project you can go through this GitHub Repository.