Make a Weather Application using Django Part 2

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

Hello everyone, today I want to continue my last article about how to make a weather application using django.This time I want to add some features such as deleting the city, preventing duplicate city in the list and many more. So, let’s do it!

If we add a city in searching bar for example “New York”, and now we will try to add the same city, there will be 2 “New York” on our list. So we have to fix that problem, type the bold part on your views.py.

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'

err_msg = ''

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

if form.is_valid():
new_city = form.cleaned_data['name']
existing_city_count = City.objects.filter(name=new_city).count()

if existing_city_count == 0:
form.save()
else:
err_msg = 'City already exists in the database!'


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)

So now if you try to add a city that had listed in our city list, it would not be appear again. Next is the city that we want to add must be exist in this world. Type the bold part on views.py.

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'

err_msg = ''
message = ''
message_class = ''


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

if form.is_valid():
new_city = form.cleaned_data['name']
existing_city_count = City.objects.filter(name=new_city).count()

if existing_city_count == 0:
r = requests.get(url.format(new_city)).json()

if r['cod'] == 200:
form.save()
else:
err_msg = 'City does not exist in this world!'
else:
err_msg = 'City already exists in the database!'


if err_msg:
message = err_msg
message_class = "is-danger"
else:
message = "City added succesfully!"
message_class = "is-success"


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,
'message' : message,
'message_class' : message_class,
}

return render(request, 'weather/weather.html', context)

Now go to the “weather.html” and add this code below row 37:

{% if message %}
<div class="notification {{ message_class }}">{{ message }}</div>
{% endif %}

Now try to run the server and you will see the description like this

If i add new city
If i add city hat doesn’t exist in the world
if i add city that already exists in the list

Now we want to allow the user to delete the city. First we want to show the delete icon, type this on “weather.html” below row 67.

<div class="media-right">
<a href="'#">
<button class="delete"></button>
</a>
</div>

Next go to views.py and type the bold part.

import requests
from django.shortcuts import render, redirect
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'

err_msg = ''
message = ''
message_class = ''

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

if form.is_valid():
new_city = form.cleaned_data['name']
existing_city_count = City.objects.filter(name=new_city).count()

if existing_city_count == 0:
r = requests.get(url.format(new_city)).json()

if r['cod'] == 200:
form.save()
else:
err_msg = 'City does not exist in this world!'
else:
err_msg = 'City already exists in the database!'

if err_msg:
message = err_msg
message_class = "is-danger"
else:
message = "City added succesfully!"
message_class = "is-success"

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,
'message' : message,
'message_class' : message_class,
}
return render(request, 'weather/weather.html', context)

def delete_city(request, city_name):
return redirect('home')

Go to “weather/urls.py” and type the bold part.

from django.urls import path
from . import views

urlpatterns = [
path('', views.index, name='home'),
path('delete/<city_name>/', views.delete_city, name='delete_city')
]

Next go to the “weather.html” and type the bold part.

<div class="media-right">
<a href="{% url 'delete_city' city_weather.city %}">
<button class="delete"></button>
</a>
</div>

Last, go to the views.py and type the bold part.

import requests
from django.shortcuts import render, redirect
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'

err_msg = ''
message = ''
message_class = ''

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

if form.is_valid():
new_city = form.cleaned_data['name']
existing_city_count = City.objects.filter(name=new_city).count()

if existing_city_count == 0:
r = requests.get(url.format(new_city)).json()

if r['cod'] == 200:
form.save()
else:
err_msg = 'City does not exist in this world!'
else:
err_msg = 'City already exists in the database!'

if err_msg:
message = err_msg
message_class = "is-danger"
else:
message = "City added succesfully!"
message_class = "is-success"

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,
'message' : message,
'message_class' : message_class,
}
return render(request, 'weather/weather.html', context)

def delete_city(request, city_name):
City.objects.get(name=city_name).delete()
return redirect('home')

Now, try to run the server and as you can see you can delete the city if you want.

So this is the end of our tutorial, hope this could be useful to anyone who wants to learn it.

Thank you and stay tune for my next articles!

--

--

Verdy Evantyo
Analytics Vidhya

Future data analyst, python enthusiast from Indonesia