Project 1:Create your own Weather App in 5 Minutes with Django and OpenWeatherAPI
Get Started with Django and OpenWeatherAPI and Build Your Own Weather App that Delivers Accurate Weather Information for Any Location in the World
Introduction
In today's world, knowing the weather conditions has become a crucial aspect of our daily lives. With the advancements in technology, it has become easier to access weather information from anywhere in the world. OpenWeatherAPI is one such tool that provides accurate and up-to-date weather information for any location in the world. In this tutorial, we will be using OpenWeatherAPI to create a weather app. By the end of this tutorial, you will have a fully functional weather app that can display weather information for any location in the world. So, let's get started!
This is my first project in which I Will be telling how I made this weather app.
You can check My Github repository for the same.
Requirements:
Account on OpenWeatherAPI.
Some Knowledge of HTML, CSS, Python.
Requests dependency
Getting Started
Firstly Create an Account on the OpenWeather API website.
Now you can copy your API key from the MY API keys tab to your notepad.
-
Let's understand a bit about this API.
How Weather API Works
To understand this you need to click on API in the Navbar.
-
Now scroll a bit and select API doc in current weather data.
-
Now you can see here how to use this API.
What are we using is getting weather from the city name.
So scroll down till you get this link with the city name and API key.
-
Here just erase {city name} and {API KEY} and enter the city you want to and your API key.
Now you will be able to a dictionary of weather information like this.
-
Now we Will create a Django project and extract this data.
Creating Django Project
Make sure you are having Django installed on your desktop.
Naming my project skyclear.
python-admin startproject skyclear
Now go into the folder cd skyclear.
Now make a home app in this.
python manage.py createapp home
Now add home in settings.py.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ]
Now in urls.py of skyclear add the path to home.
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('home.urls')), ]
Now create a file named urls.py in home and this data.
from django.urls import path,include from . import views urlpatterns = [ path('', views.home, name="showhome"), ]
Now in views.py add a function that renders our home page.
from django.shortcuts import render # Create your views here. def home(request): return render(request,"home/home.html",context={})
Now the first test is it working or not.
python manage.py runserver
Creating our Front end
Create a folder in home templates/home.
Now create a file named home.html.
Now Create the Front end according to you.
In this project, I have used bootstrap.
And Code for the same is:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SkyClear</title> <link rel="icon" href="./13d.png"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <style> .card { margin: 10% auto; float: none; margin-bottom: 10px; } </style> </head> <body> <nav class="navbar navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand">SkyClear</a> <form class="d-flex"> <input class="form-control me-2" name="entered_city" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </nav> <div class="card mb-3 " style="max-width: 440px;"> <div class="row g-0"> <div class="col-md-4 mx-auto" style = "{backgroundImage : http://openweathermap.org/img/wn/{{}}.png}"> <img src="http://openweathermap.org/img/wn/{{}}.png" class="img-fluid rounded-start" alt={{city}}> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title"> - </h5> <p class="card-text">Temperature(°C): °C</p> <p class="card-text">Temperature(K): K</p> <p class="card-text"><small class="text-muted">Humidity: - Pressure: Pa </small></p> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
Now our Front end is also ready. Now, let's start adding the data from API.
Fetching data from API
For getting data we need a requests library.
You can check their Documentation.
Type pip install requests in the terminal to install requests.
Now just import requests in views.py.
Now let's write code for fetching data.
from django.shortcuts import render import requests # Create your views here. def home(request): city="patiala" url=f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={apikey}' data = requests.get(url).json() print(data) return render(request,"home/home.html",context={})
Now we got data from API you can check it in the terminal after refreshing the home page.
Fetching Required information
Now you can see all the data in your terminal.
Now as we do in a python dictionary fetch the data in the same manner.
My code for the same is given below.
from django.shortcuts import render import requests # Create your views here. def home(request): city="patiala" url=f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={apikey}' data = requests.get(url).json() payload={'city':data['name'], 'weather':data['weather'][0]['main'], 'icon':data['weather'][0]['icon'], 'celcius_temperature':data['main']['temp'], 'kelvin_temperature':int(data['main']['temp'])-273, 'pressure':data['main']['pressure'], 'humidity':data['main']['humidity'], 'description':data['weather'][0]['description'], } return render(request,"home/home.html",context={'data':payload})
So we got all the data in the payload we required for a weather app.
Now just send this data in context to our front end.
Displaying data on the front end
Now we got all the data on our HTML page.
Just use Ginger Coding and add all the data in HTMLpage as I did below in this code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SkyClear</title> <link rel="icon" href="./13d.png"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <style> .card { margin: 10% auto; float: none; margin-bottom: 10px; } </style> </head> <body> <nav class="navbar navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand">SkyClear</a> <form class="d-flex"> <input class="form-control me-2" name="entered_city" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </nav> <div class="card mb-3 " style="max-width: 440px;"> <div class="row g-0"> <div class="col-md-4 mx-auto" style = "{backgroundImage : http://openweathermap.org/img/wn/{{data.icon}}.png}"> <img src="http://openweathermap.org/img/wn/{{data.icon}}.png" class="img-fluid rounded-start" alt={{data.city}}> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title">{{data.city}} - {{data.description}}</h5> <p class="card-text">Temperature(°C): {{data.celcius_temperature}}°C</p> <p class="card-text">Temperature(K): {{data.kelvin_temperature}} K</p> <p class="card-text"><small class="text-muted">Humidity: {{data.humidity}} - Pressure:{{data.pressure}} Pa </small></p> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html>
So we are Good to go just run the server and you will see the data.
But here we are manually adding the city in our code, So to get user input let's to start a get request service.
How to get weather information of the city dynamically
Just write a simple code as you write for getting a GET requests.
As in the navbar, we are already having a form.
Just name the form and in views.py fetch the data.
And add this data in URLAs I did below.
from django.shortcuts import render import requests # Create your views here. def home(request): city=request.GET.get('entered_city') # city="patiala" url=f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={apikey}' data = requests.get(url).json() payload={'city':data['name'], 'weather':data['weather'][0]['main'], 'icon':data['weather'][0]['icon'], 'celcius_temperature':data['main']['temp'], 'kelvin_temperature':int(data['main']['temp'])-273, 'pressure':data['main']['pressure'], 'humidity':data['main']['humidity'], 'description':data['weather'][0]['description'], } return render(request,"home/home.html",context={'data':payload})
So our project has been finished Successfully. Just Run the server and you are good to go.
How our project now looks like?
So this is what our project looks like. I think being a basic project this will also help you in learning more about Django.
Make Sure to follow me on hashnode.
Having any Querry? Ask me.