Weather App Using Django

In this tutorial, we’ll use Django to build a weather app that displays the weather of the cities we’ve searched. It’s a simple Django project that shows beginners the fundamentals of the language. We’ll also get the data from the Weather API.

Make sure you have Python and Django installed before continuing with this tutorial. You may use the pip command to install Django if it isn’t already installed. We recommend setting up the virtual environment first, then installing Django.

We have already discussed in the last tutorials how to set up a virtual environment and how to install Django.

Create Project and App

If you haven’t installed Django yet I recommend you first install Django. then create a project using this command and I must recommend opening any IDE before moving ahead.

django-admin startproject project_name

After running the above command your project directory looks like this: I use project name as weather you can name any it depends on you.

0

Now First, you have to go weather directory which we have created above by using the cd command.

1

Now Using the command below, we build a new app called MyWeatherAPP.

python manage.py startapp MyWeatherAPP

After the above command your directory looking like this:

2

Now we have to include our MyWeatherAPP in settings.py so open up and add it into INSTALLED_APPS:

3

We are one step closer to completing our application at this moment. Use the following command to start the server.

python manage.py runserver
4

The Django application environment will be displayed if you click on the provided link.

5

Now we have to login into the admin panel which we will cover in the next step.

Logging to Admin Panel

After that, we’ll use the built-in Django Dashboard. To do so, we’ll need to migrate our database, which will need Django to construct the pre-defined tables required by default applications.

In the terminal press ctrl+c to stop the server and, type the following command, and hit the enter key:

python manage.py migrate  
Weather App6

This will create our project’s SQLite database. It’s a default database provided by Django, and it’s got a bunch of tables in it. and you noticed in your directory that db.sqlite3 is created.

Weather App7

In the admin panel, there will be a user table that will hold the user in our app. To access the admin panel, use the command below to establish an admin account.

python manage.py createsuperuser
Weather App8

Following the execution of the command, the user will be prompt for information such as their login, email address, and password. After that, use the command below to restart the server.

python manage.py runserver

Because admin is set up in the url.py, open the given link and go to http://127.0.0.1:8000/admin.

Weather App9

Now it’s time to add a template and create our project.

Adding Template and View

First, we have to set up our Url setting, so create a file in weather/MyWeatherAPP called urls.py and paste this code.

from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="home")
]

and in weather/weather directory paste the following code in urls.py which is already built-in.

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

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

Now create a templates folder in weather/MyWeatherAPP. A template is an HTML file that permits the Jinja syntax to be add to make the template dynamic. In this folder create any HTML file in my case I created as home.html.

Weather App10

paste the following code in templates/home.html

<!DOCTYPE html>  
<html lang="en">  
{% load static %}  
  
<head>  
  <meta charset="UTF-8" />  
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.5.3/cerulean/bootstrap.min.css"  
    integrity="sha512-dQLT/B7byn2LjN/DN4zeBKpwGV6qbidV0XiMRWQOL7TGrV7FkZFldkGG+DGMU+CQnMTcRZlUI7GMWt1j6akNew=="  
    crossorigin="anonymous" />  
  <title>Weather App </title>  
</head>  
  
<body>  
   
  <br /><br /> <br>  
  <div id="jumbotron" class="jumbotron" style="text-align: center; margin-top:-50px">  
    <h1 class="display-4">Weather Desktop App </h1>  
    <h5>Using Python Language and Django Framework</h5>  
  </div>  
  
  <nav class="navbar navbar-expand-lg navbar-dark bg-primary">  
    <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>  
  </nav>  
  <br> <br>  
  <div class="row">  
  {% if country_code and coordinate and temp and pressure and humidity %}  
                <div class="col d-flex justify-content-center" ">  
        <div class=" card text-white bg-light mb-6">  
        <div class=" card-body">  
        <h4><span class="badge badge-primary">City :</span> </h4>  
            <h4><span class="badge badge-primary">Country Code :</span> </h4>  
            <h4><span class="badge badge-primary">Coordinates [X,Y] :</span> </h4>  
            <h4><span class="badge badge-primary">Temperature :</span> {{temp}}</h4>  
            <h4><span class="badge badge-primary">Pressure :</span> </h4>  
            <h4><span class="badge badge-primary">Humidity : </span> </h4>  
        </div>  
        {% endif %}  
 </div>  
</body>  
  
</html>

and make changes in views.py

from django.shortcuts import render  
  
# Create your views here.  
  
def home(request):  
    return render(request, 'home.html', {})  

The URL without an endpoint will be match by Django and sent to the view function we built.

Using the Weather App API

We’ll need to sign up for the Open Weather Map API to acquire a real-time weather report. It will provide real-time weather information for any city we add to our app.

Visit the site, create an account, and then go to their dashboard’s API keys.

Weather App11

Add the city, city_weather, and import the requests module.

Note: To prevent other parties from using the API key, it should be kept private.

views.py

import json  
from django.shortcuts import render  
import urllib.request  
import json  
  
# Create your views here.  
  
def home(request):  
    if request.method == 'POST':  
        # Get the city name from the user api = http://api.openweathermap.org/data/2.5/weather  
        city = request.POST.get('city', 'True')  
          
        # retreive the information using api  
        source = urllib.request.urlopen('http://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=imperial&appid=164fec96a27b97680ee442e489ce3f06').read()  
          
        # convert json data file into python dictionary  
        list_of_data = json.loads(source)  
  
        # create dictionary and convert value in string  
        context = {  
            'city': city,  
            "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',  
            "pressure": str(list_of_data['main']['pressure']),  
            "humidity": str(list_of_data['main']['humidity']),  
        }  
    else:  
        context = {}  
      
    # send dictionary to the home.html  
 
    return render(request, 'home.html', {}) 

 

We verify if the method is POST in the above view, then obtain the city name from the form. Then, using urllib.request.urlopen(), we read the data of a given city. The source variable is sent to json.loads(), which converts the data to a Python dictionary.

We can quickly get the data we need and store it in the context dictionary using this method. When the user inputs the city, all of the properties that we have saved in the context dictionary will be shown.

Now we will make changes to the HTML file. paste the following code in home.html

<div class="row">  
        {% if country_code and coordinate and temp and pressure and humidity %}  
        <div class="col d-flex justify-content-center" ">  
        <div class=" card text-white bg-light mb-6">  
        <div class=" card-body">  
        <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>

Now we’ll start the server and click the provided URL. It will appear as seen below.

Weather App12

Enter the name of the city in the search box, hit the search button, and the weather data will appear. We enter Pakistan and obtain weather information.

Weather App13

Conclusion – Weather App

We have built a weather app using the Django framework, as seen in the following screenshot. We’ve learned about various commands so far, as well as how to create a virtual environment and, most importantly, how to use the API. We’ve also spoken about using an API to acquire the country code, humidity, and temperature of several weather data.

You may improve the project’s user interface. We utilized HTML and Bootstrap classes.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

If you want to learn more about the Django programming language then click the link to see our last article How to install Django in Windows

Leave a Comment