Creating a Weather App in Django- Part3

So we will continue to build our weather app from where we left in this post: “Creating a Weather App in Django- Part2“.

So in this post we are going to build a table in the database.So for building that table we will create one model.

So make a model named City in the weather/models.py file as following:

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'

After that register that model in the admin.py file as following:

from django.contrib import admin
from .models import City

admin.site.register(City)

After that to create a migration file run the command python manage.py makemigrations in the command prompt.

After creating a migration file,to apply that migration file to your project run this command python manage.py migrate in the command prompt.

To check whether your model in registered in the admin section or not,you can run the server and check the admin section.

So for checking purpose just add three cities in the admin section as following:

weather-appAfter that change the weather/views.py file as following to loop over multiple cities:

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

# Create your views here.
def index(request):
    #units as imperial is that we will get a temperature as fahrenheit
    #q is a placeholder,which is the name of city we are going to send
    url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=API_KEY'
    cities = City.objects.all()

    #List to store details about all cities
    weather_data = []


    for city in cities:
    #.json will convert the result into a json object
    # we were converting it into json because json object can be easily represented by python list or dictionary
        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)

After that change the weather.html template as following to loop over all cities that are present in database as following:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.css" />
</head>

<body>
    <section class="hero is-primary">
        <div class="hero-body">
            <div class="container">
                <h1 class="title">
                    What's the weather like?
                </h1>
            </div>
        </div>
    </section>
    <section class="section">
        <div class="container">
            <div class="columns">
                <div class="column is-offset-4 is-4">
                    <form method="POST">
                        <div class="field has-addons">
                            <div class="control is-expanded">
                                <input class="input" type="text" placeholder="City Name">
                            </div>
                            <div class="control">
                                <button class="button is-info">
                                    Add City
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </section>
    <section class="section">
        <div class="container">
            <div class="columns">
                <div class="column is-offset-4 is-4">
                    {% for city_weather in weather_data %}
                    <div class="box">
                        <article class="media">
                            <div class="media-left">
                                <figure class="image is-50x50">
                                    <img src="http://openweathermap.org/img/w/{{ city_weather.icon }}.png" alt="Image">
                                </figure>
                            </div>
                            <div class="media-content">
                                <div class="content">
                                    <p>
                                        <span class="title">{{ city_weather.city }}</span>
                                        <br>
                                        <span class="subtitle">{{ city_weather.temperature }}</span>
                                        <br>{{ city_weather.description }}
                                    </p>
                                </div>
                            </div>
                        </article>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </section>
    <footer class="footer">
    </footer>
</body>

</html>

After this all changes in the views.py field and in the weather.html file if you run the server then you will be able to see the following in the hompage.
weather-app

So from the above image you are able to see all cities with there temperature,weather description and icon.

So in the next post we will create one form which will take city from user.


This is all about how to add model to store cities in database.

Leave a Comment

Your email address will not be published. Required fields are marked *