Make a Weather Application using Django

Verdy Evantyo
Analytics Vidhya
Published in
4 min readDec 24, 2019

Hello, this time I want to share about how to make a weather application with django. This weather application will show you about the temperature with some cloud description in a city that we want to know. Lets do it!

First you have to run this on your terminal to install the django.

django-admin startproject the_weather
cd the_weather
python manage.py startapp weather

And then open settings.py and add ‘weather’ on INSTALLED_APPS. Then we want to create a superuser on our website first, run this on your terminal.

python manage.py migrate
python manage.py createsuperuser

And then fill in the blank with your own username and password. Next, try to run the website by typing python manage.py runserver in your terminal, and fill the username and password that have you made before.

Next is make a file directory inside ‘weather’ directory named ‘templates’, and make a new file directory inside ‘templates’ directory named ‘weather’, and inside the ‘weather’ directory make a new HTML file named ‘weather.html’, delete the code in HTML, copy the HTML code from https://github.com/Verdyevan/Weather_App/blob/master/the_weather/weather/templates/weather/weather.html, and paste in ‘weather.html’.

On urls.py type like this

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

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

Make a new python file inside ‘weather’ directory named ‘urls.py’, and type this code in it

from django.urls import path
from . import views

urlpatterns = [
path('', views.index),
]

And then type this code on views.py, and try to run the server by typing python manage.py runserver on your terminal.

from django.shortcuts import render

def index(request):
return render(request, 'weather/weather.html')

After that run ‘pipenv install requests’ in the terminal and while waiting for installation you can add some code on views.py to set the api on your website like this.

import requests
from django.shortcuts import render

def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=271d1234d3f497eed5b1d80a07b3fcd1'
city = 'Las Vegas'

r = requests.get(url.format(city)).json()

city_weather = {
'city': city,
'temperature': r["main"]["temp"],
'description': r["weather"][0]["description"],
'icon': r["weather"][0]["icon"],
}
context = {'city_weather' : city_weather}
return render(request, 'weather/weather.html', context)

Go to the weather.html and change the code to this.

  • For changing the city type this at row 56 <span class=”title”>{{ city_weather.city }}</span>
  • For changing the temperature type this at row 58 <span class=”subtitle”>{{ city_weather.temperature }}° F</span>
  • For changing the description type this at row 59 <br> {{ city_weather.description }}
  • For changing the icon type this at row 50 <img src=”http://openweathermap.org/img/w/{{ city_weather.icon }}.png” alt=”Image”>

Try to run the code and it will be changed to the current weather at that city. It will works but only one city and we have to change the city in views.py if we want to change the another current city weather. So type this on models.py.

from django.db import models

class City(models.Model):
name = models.CharField(max_length=25)

def __str__(self):
return self.name

class Meta:
verbose_name_plural = 'cities'

Run python manage.py makemigrations and python manage.py migrate on your terminal. And type this on admin.py.

from django.contrib import admin
from .models import City

admin.site.register(City)

Run the server and look to the admin site and add some cities like this.

We want to display current weather in these three cities on our website. So if we want to do that add some code on views.py like this.

import requests
from django.shortcuts import render
from .models import City

def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=271d1234d3f497eed5b1d80a07b3fcd1'
city = 'Las Vegas'

cities = City.objects.all()

weather_data = []

for city in cities:
r = requests.get(url.format(city)).json()

city_weather = {
'city': city.name,
'temperature': r["main"]["temp"],
'description': r["weather"][0]["description"],
'icon': r["weather"][0]["icon"],
}
weather_data.append(city_weather)

context = {'weather_data' : weather_data}
return render(request, 'weather/weather.html', context)

And then go to ‘weather.html’ and type:

  • On row 46 type {% for city_weather in weather_data %}
  • On row 66 type {% endfor %}

You will get like this.

Make a new python file inside the weather directory named ‘forms.py’.

And then type this on it.

from django.forms import ModelForm, TextInput
from .models import City

class CityForm(ModelForm):
class Meta:
model = City
fields = ['name']
widgets = {'name' : TextInput(attrs={'class' : 'input', 'placeholder' : 'City Name'})}

Back to the views.py and type this.

import requests
from django.shortcuts import render
from .models import City
from .forms import CityForm

def index(request):
url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=271d1234d3f497eed5b1d80a07b3fcd1'

if request.method == "POST":
pass

form = CityForm()

cities = City.objects.all()

weather_data = []

for city in cities:
r = requests.get(url.format(city)).json()

city_weather = {
'city': city.name,
'temperature': r["main"]["temp"],
'description': r["weather"][0]["description"],
'icon': r["weather"][0]["icon"],
}
weather_data.append(city_weather)

context = {'weather_data' : weather_data, 'form' : form}
return render(request, 'weather/weather.html', context)

On ‘weather.html’ change some code to this :

  • Delete row 29 and change to {{ form.name }}
  • At row 33 type code like this <button type=”submit” class=”button is-info”>
  • Below row 26 type code like this {% csrf_token %}

Last, if we type a city in searching bar and submit it, we want to display current weather at that city, so on your views.py, below row 8 type like this.

if request.method == "POST":
form = CityForm(request.POST)
form.save()

Try to run the server and add some cities, and you will get what you want.

So that’s it for this tutorial, for next article maybe i want to share about this website development like you can delete the city or add some description or something.

Thank you and stay tune for my next articles!

--

--

Verdy Evantyo
Analytics Vidhya

Future data analyst, python enthusiast from Indonesia