Basic settings —
Change directory for weather —
cd weather
Start server —
python manage.py runserver
To check if the server is running or not, go to your web browser and enter http://127.0.0.1:8000/
URL quality. You can now stop the server by pressing
ctrl-c
Implementation:
python manage.py startapp main
Go to main / folder by executing:
cd main
and create a folder with the file index.html
: templates / main / index.html
Open the project folder with a text editor. The directory structure should look like this:
Now add the main application to settings.py
Edit urls.py
in the weather:
from django.contrib import admin from django .urls import path, include urlpatterns = [ path ( ’admin /’ , admin.site.urls), path (’ ’, include (’ main.urls’)), ] |
edit your urls.py
file basically:
from django.urls import path from . import views urlpatterns = [ path (’’, views.index), ] |
edit views.py to mostly:
from django.shortcuts import render # json import to load json data into python dictionary import json # urllib. request make a request to api import urllib.request def index (request): if request.method = = ’POST’ : city = request .POST [ ’city’ ] The API key may have expired, please use your own api_key put api_key instead of appid = & quot; your_api_key_here & quot; & # 39; & # 39; & # 39; # source contains JSON data from the API source = urllib.request.urlopen ( ’ http://api.openweathermap.org/data/2.5/weather?q =’ + city + ’& amp; appid = your_api_key_here’ ). read () # convert JSON data into a dictionary list_of_data = json.loads (source) # data for the list_of_data variable data = { "country_code" : str (list_of_data [ ’ sys’ ] [ ’country’ ]), "coordinate" : str (list_of_data [ ’coord’ ] [ ’ lon’ ]) + ’’ + str (list_of_data [ ’coord’ ] [ ’lat’ ]), "temp" : str (list_of_data [ ’ main’ ] [ ’temp’ ]) + ’ k’ , "pressure" : str (list_of_data [ ’main’ ] [ ’pressure’ ]), "humidity" : str (list_of_data [ ’main’ ] [ ’ humidity’ ]), } print (data) else : data = {} retur n render (request, "main / index.html" , data ) |
You can get your own API key from: Weather API
Go to templates / main / index.html
and edit it : link to file index .html
Make migrations and migrate this:
python manage.py makemigrations python manage.py migrate
Now let’s start the server to see your weather app.
python manage.py runserver