Building weather application by leveraging Django framework in Python language
Create a Weather app using Django that allows users to enter a city name and view current weather details, such as temperature, humidity, and pressure. Here's a step-by-step guide to building the app:
Prerequisites:- Familiarize yourself with Django basics and installation.
Basic Setup
- Create a virtual environment and install the necessary packages:
Step 1: Create a Django Project
Start a new Django project named "WeatherApp":
Step 2: Navigate to the Project Directory
Step 3: Create a Django App
Create an app called "weather":
The directory structure should appear as follows:
Step 4: Add the weather App to Settings
Open and include 'weather' to the list:
Step 5: Configure URLs
Modify to include the weather app views:
```pythonfrom django.contrib import adminfrom django.urls import path, include
urlpatterns = [ path('admin/', admin.site.urls), path('', include('weather.urls')),]```
Step 6: Define URLs for the weather App
Create and define the following:
```pythonfrom django.urls import pathfrom . import views
urlpatterns = [ path('', views.weather_view, name='weather_view'),]```
Step 7: Create the View
Edit to fetch, process, and display weather data:
```pythonimport requests
def weather_view(request): if request.method == 'POST': city = request.POST.get('city') api_key = "your_api_key_here" # Replace with your OpenWeatherMap API key base_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" response = requests.get(base_url) weather_data = response.json()
```
Step 8: Create the Template
Create with the following content:
```html
{% if temperature %}
Temperature: {{ temperature }}°C
Humidity: {{ humidity }}%
Pressure: {{ pressure }} hPa
{% endif %}
```
Step 9: Run the Server
Start the Django development server:
Navigate to "http://127.0.0.1:8000/" in your browser, enter a city name, and check the weather!
Next Article: Building a Sign Up and Login System with Confirmation Email in Django | Python
Incorporating technology, the Weather app built with Django allows users to access weather details such as temperature, humidity, and pressure for a given city. To achieve this, the app fetches weather data from the OpenWeatherMap API using technology like requests and Python.