Weather App in Djnago
First let’s have the api_key .
Click here to go to the website of weather api. Create an account and get the api key .
Weather api provides different services but for out project we will be using ->
Now Assuming you have the api key ….
Create a project
django-admin startproject WeatherApp
Enter into the WeatherApp folder and run->
python manage.py startapp example
Final folder structure
Register the app in the project .In settings.py of the “weather” folder
In the project level urls.py file add
from django.contrib import adminfrom django.urls import path,includeurlpatterns = [path('admin/', admin.site.urls),path('',include('example.urls'))]
In the app folder create urls.py file and add
from django.urls import path,includefrom . import viewsurlpatterns = [path('',views.getdata,name="getdata")]
In models.py create a new model ->
from django.db import models# Create your models here.class Weather(models.Model):place = models.CharField(max_length=250)description=models.CharField(max_length=250)
Now we have to register the model in admin.py
from django.contrib import adminfrom .models import Weather# Register your models here.admin.site.register(Weather)
In the app level views.py add (Make sure to indent the code)
from django.shortcuts import renderimport requestsfrom .models import Weather# Create your views here.def getdata(request):base_url = "http://api.openweathermap.org/data/2.5/weather?"if(request.method=="POST"):city_name=request.POST['city_name']API_KEY="0f511e87f0d6cd2622d48ef8805fbd46"URL=base_url+"q="+city_name+"&appid="+API_KEYdata = requests.get(URL).json()description = data['weather'][0]['description']temp = data['main']['temp']feels_like = data['main']['feels_like']humidity = data['main']['humidity']place = data['name']weather = Weather.objects.create(place=place,description=description)previous_search = Weather.objects.all()context={'description':description,'temp':temp,'feels_like':feels_like,'humidity':humidity,'place':place,'prev':previous_search}print(previous_search)print(data)return render(request,'index.html',context)return render(request,'index.html')
Run the following commands to make required database tables
python manage.py makemigrations
python manage.py migrate
Make a .html file inside the templates folder
Name it index.html and add
<!doctype html><html lang="en"><head><!-- Required meta tags --><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><!-- Bootstrap CSS --><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"><title>Weather</title></head><body><form action="/" method="post">{% csrf_token %}<div class="input-group"><span class="input-group-text">Enter city name</span><input type="text" name="city_name" class="form-control"></div></form><div class="card"><div class="card-body" style="text-align: center;">You have searched for {{ place }}</div></div><div class="card"><div class="card-body">Description of the weather : {{ description }}</div></div><div class="card"><div class="card-body">Temp in kelvin : {{ temp }} but feels like {{feels_like}}</div></div><div class="card"><div class="card-body">Humidity : {{ humidity }}</div></div><h3>Previous searched places</h3>{% for p in prev %}<div class="card-body">City{{ p.place }} and Temperature is {{ p.description }}</div>{% endfor %}<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script></body></html>
Run “python manage.py createsuperuser” to create an admin . After successful creation run “python manage.py runserver” to spin up the server
open the link in a browser and go to “http://127.0.0.1:8000/admin” . You will see something like this
After login you will see the search history of this site
def __str__(self):return self.description
In that case your models.py will look like
from django.db import models# Create your models here.class Weather(models.Model):place = models.CharField(max_length=250)description=models.CharField(max_length=250)def __str__(self):return self.description
The final result
Takeaways
- We can interact with databases without writing SQL instead we can use python classes.
- We can dynamically send data to html with “Jinja” .
- Built-in robust admin panel.
- csrf_token for added security.
- Django comes batteries included.