Django Web Application Sample
-
Here we are going to create a Python web application using Django framework. Django is a high-level framework written in Python and compared to some other simpler frameworks like Flask, Django has many features to develop bigger and complex web applications.
Follow this step by step tutorial to understand the basics of Django based Python web application development. Basic CRUD operations are be implemented here. To store the data a json file is used.
-
Python Initial Setup
Download and install the latest version of python from Python Website.
Keep your favourite Python editor ready. This can be a basic notepad application available by default for your OS or you can download and install any free editor like VS Code.
Next, create a virtual environment.
For that, go to the command prompt and cd to the folder where you are going to keep your project.
Run command python -m venv CarSalesVENV to create a project folder CarSales and a virtual environment for it.
Activate the VE using command:For Windows:CarSalesVENV\Scripts\activate.batFor Linux, macOS:source CarSalesVENV /bin/activateAfter VE activation, from cmd type cd CarSalesVENV to navigate to the project folder.
-
Install Django
To install Django, run below command. This will install Django and associated libraries to your VE.
pip install django
Run pip freeze to check if Django installed successfully. Should give an output like this.asgiref==3.4.1 Django==3.2.9 pytz==2021.3 sqlparse==0.4.2
-
Application Initial Setup
A Django application is structured as a top level Django Project with zero or more Django Apps (modules) within it. Project will contain common codes specific to all sub apps.
For our example, we will create a project within our virtual environment and an app inside it. We will explain the initial setup in multiple steps.Step 1: Create Django Project
To create a project run:
django-admin startproject CarSalesProject .
Running the above command will create a project named CarSalesProject and a python file manage.py will get added. We are providing a ' .' after the project name to avoid an additional folder with the same name being created. See the folder structure after creating project.Step 2: Create Django App
Now on, we don't have to use django-admin in our commands. Use the below command to create our CarSales app.
python manage.py startapp CarSales
A new app folder will get created with some files in it. For more details on the files created, you can refer Django Basics.
New folder structure below:Step 3: Include app to our project
For this, in settings.py, add our new app CarSales (case sensitive) to INSTALLED_APPS list as below.
-
Loading First HTML Page
This part explains how we are going to define the routes and where to place our html files. We are going to work on four files highlighted in below image. An html page and 2 urls.py file and a views.py file.
Html files should be placed within a folder named templates. Create this folder in our CarSales app.Add a new html file carslist.html, inside templates folder.
We should have 2 urls.py, one inside, project folder and one inside app folder. If not available, create these files. urls.py in project folder adds a reference to the app urls.py.
In app urls.py we define the urlpatterns for this module.
In views.py we define the htmls to render for each route. Code provided below.Run the app using command python manage.py runserver
Copy the url from cmd and browse. We should get below output window. -
Setting up data
This tutorial mainly focuses on Django. So, we are not going for a backend database and will keep the data in a json file. Create a folder named json-data inside CarSales app and place a file carslist.json in this folder.
Copied[ {"id":"1", "name":"Toyota Camry", "year":"2018", "price":"2000"}, {"id":"2", "name":"Honda Civic", "year":"2019", "price":"2200"}, {"id":"3", "name":"Chevrolet Silverado", "year":"2017", "price":"1800"}, {"id":"4", "name":"Ford F-150", "year":"2020", "price":"2500"}, {"id":"5", "name":"Nissan Altima", "year":"2021", "price":"3000"} ]
-
List
carslist.html is going to hold the list of cars available for sale. To list the items, add below code in the body of html. Here, we using a for loop to bind the data to a table.
Now modify views.py as below to read the json data and bind it to the html using render function.For styling we will use Bootstrap 5. Add below 2 lines inside head of html.
<link rel="stylesheet" crossorigin="anonymous" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" > <script crossorigin="anonymous" src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" > </script>
On refreshing the web page, we will get the below output window.
-
Create
Add a new button in the carslist.html above the table.
<a class="btn btn-primary" href="addcar">Add New Car</a>
Add a new url pattern for addcar in the app urls.py.
from django.urls import path from . import views urlpatterns = [ path('', views.carslist, name = 'carslist'), path('addcar', views.addcar, name = 'addcar') ]
Add new html file addcar.html in templates folder and place below code.
Html uses forms. To handle forms in Django we need a form class. Add an new file forms.py in the CarSales app folder and include the form details.
Then add below code in view.py as the second function below carslist function.Also import the form class and redirect in view.py
from django.shortcuts import render, redirect from django.apps import apps import json from .forms import CarForm
In the view.py, we are defining a new function for addcar. We are using the same method for GET and POST. GET is just rendering addcar.html. In POST, we are reading data from form controls and save data to json file and then redirect to list page.
In HTML page, we are defining a form with 4 text boxes. Each has a name provided. This name is used in the view.py while reading data from controls.
In the HTML form, we have to add {% csrf_token %} next to form tag to avoid csrf verification failed error. On rerun, we can navigate to Create page as below and add new Car. -
Update
For update and delete we will add 2 links in the carslist.html page as below.
Copied<table class="table"> <thead> <tr> <th scope="col">Id</th> <th scope="col">Name</th> <th scope="col">Year</th> <th scope="col">Price</th> <th scope="col">Edit</th> <th scope="col">Delete</th> </tr> </thead> <tbody> {% for car in cars %} <tr> <td>{{ car.id }}</th> <td>{{ car.name }}</td> <td>{{ car.year }}</td> <td>{{ car.price }}</td> <td><a href='updatecar/{{ car.id }}'>Edit</a></td> <td><a href='deletecar/{{ car.id }}'>Delete</a></td> </tr> {% endfor %} </tbody> </table>
For easier understanding, we are going to keep separate routes for create and update, although we are using the same addcar.html for update also. For update we will provide the route name updatecar.
In addcar.html, in order to populate the values, we have to use the value attribute and bind the car object values as in html provided below.
In views.py, add new updatecar function. In GET, we are filtering the list based on selected id using Python List Comprehension and pass it to the addcar.html page.
In POST, we loop through cars list and if id matches, value is changed and updated.
Note: We have to disable Id textbox to not make changes to Id. Here we are not doing it and if Id is changed no update will happen.Add a new url pattern for addcar in the app urls.py.
from django.urls import path from . import views urlpatterns = [ path('', views.carslist, name = 'carslist'), path('addcar', views.addcar, name = 'addcar'), path('updatecar/<int:id>', views.updatecar, name = 'updatecar') ]
After the above changes, update will work, but create will throw an error. To fix this, change the render line of addcar as below.
return render(request, 'addcar.html', {'car':{}})
We are binding an empty car object to make it working.
-
Delete
For delete, we will add a new route deletecar. We will loop through the list and remove selected item. If needed, a confirm popup also can be added.
Copieddef deletecar(request, id): with open(jsnfile) as cr: cars = json.load(cr) newcarlist = [] for car in cars: if(str(car['id']) != str(id)): newcarlist.append(car) with open(jsnfile, 'w') as cw: json.dump(newcarlist, cw) return redirect('carslist')
Then add new url pattern for deletecar in the app urls.py.
from django.urls import path from . import views urlpatterns = [ path('', views.carslist, name = 'carslist'), path('addcar', views.addcar, name = 'addcar'), path('updatecar/<int:id>', views.updatecar, name = 'updatecar'), path('deletecar/<int:id>', views.deletecar, name = 'deletecar') ]
-
Complete code
Below listed are the files with code changes. Also a one line change required in Settings.py which is explained at the beginning.
-
Other web app samples
Crud Samples implemented using different frameworks and databases.