In this Python Django tutorial, I will explain to perform Django CRUD with bootstrap Template.
I was given a project to develop an application for a fitness club gym that would register gym members, show their information, update their fitness records, and delete members who left the gym.
In order to conduct CRUD activities on the GymSystem Project, I used a class-based generic view, and to enhance its appearance, I used bootstrap.
Here, we will see:
- Why use Django Crispy Forms for bootstrap
- How to perform Django CRUD operation using class-based generic view
- How to perform CRUD operation with bootstrap in Django
- How to build gym registration system using class-based generic view and bootstrap in Django
- How to use Django Crispy Forms to implement bootstrap
- How to use various controls like textbox, radio button, select field, and help_text in Django
At the end of this article, you can also download the code Django CRUD with bootstrap template.
How to perform Django CRUD with bootstrap Template
Now, let us see, step by step how to perform CRUD operation with a bootstrap template in Python Django.
Why use Django Crispy Forms for bootstrap
Django has a Python package called django-crispy-form that has built-in support for the Bootstrap CSS and Bootstrap CDB framework. It makes it easier for us to include Bootstrap in our project with fewer lines of code.
How to setup Django Crispy Forms
Installing django-crispy-forms in our activated virtual environment is the first step. This package allows us to render Django forms without the need for any additional custom CSS.
Type the below-given command in the terminal to install crispy forms in Django.
pip install django-crispy-forms
When the installation is completed, add the Django crispy forms to INSTALLED_APPS in the settings.py file.
The CRISPY_TEMPLATE_PACK should now be added after the list of INSTALLED_APPS to offer built-in support for multiple CSS and Bootstrap frameworks and set its value equivalent to the bootstrap that we are using.
Here I, set its value to bootstrap4 as given below.
CRISPY_TEMPLATE_PACK = 'bootstrap4'
Read: How to delete session property in Django
How to perform CRUD operation using class-based generic view with bootstrap
Now, we will see an example of how to use a bootstrap template to develop a gym registration application that handles CRUD operations.
Django Project Setup
Open the terminal and type the following command to begin a Django project. Here, GymRegistrationProject is the name of the Django Project.
django-admin startproject GymRegistrationProject
It will make a folder called GymRegistrationProject and to enter into the project, type the below command in the terminal.
cd GymRegistrationProject
Create a Django app named MyApp inside this project folder, by typing the below command in the terminal.
python manage.py startapp MyApp
To activate this app, add its name to the INSTALLED_APP list in the settings.py file.
Django by default provides a urls.py file to map the newly created app inside of it in the project directory. Add the code below to it to do this.
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('MyApp.urls')),
]
Read: How to get user IP address in Django
Create a model in Django
To build models, open the models.py file in the app directory and add the following code there.
from django.db import models
# Create your models here.
select_state = (
("new york", "New York"),
("california", "California"),
("iiiinois", "IIIinois"),
("texas", "Texas"),
("arizona", "Arizona"),
("massachusetts", "Massachusetts"),
("nevada", "Nevada"),
("south carolina", "South Carolina"),
)
select_gender = (
("male", "Male"),
("female", "Female"),
("other", "Other"),
)
class MemberRegistration(models.Model):
name = models.CharField(max_length=25)
gender = models.CharField(max_length=10,choices=select_gender,default='male')
date_of_birth = models.DateField(help_text='Enter date in YY-MM-DD format')
personal_address = models.CharField(max_length=60)
city = models.CharField(max_length=20)
state = models.CharField(max_length=30,choices=select_state,default='new york')
email = models.EmailField()
weight = models.DecimalField(max_digits=5,decimal_places=2)
def __str__ (self):
return "%s"%(self.name)
Here, we create a model class MemberRegistration which has the following fields.
- The name, city, and personal_address are Django CharField. And there is a 25, 20, and 60-character limit for these character fields respectively.
- The email is Django EmailField which allows saving email addresses.
- The date_of_birth is Django DateField. In order to determine the format of the input date, we additionally add the help_text attribute.
- The gender and state are Django CharField. And there is a 10 and 30-character limit for these character fields respectively. Additionally, there is a choices attribute that will be used as options for fields and consists of iterables for items we define in a tuple named select_gender and select_state.
- And to change the display name of the object in the Django model use the def __str__(self). It will render the item name as name, as we return the self.name.
In order for the user to view the MemberRegistration model in the admin application, register it on the admin site. Add the following code to the admin.py file by opening it.
from django.contrib import admin
from .models import MemberRegistration
# Register your models here.
admin.site.register(MemberRegistration)
Migrate Django Model
To make a migration file that includes code for a model’s tabular schema type the below command in the terminal.
python manage.py makemigrations
To builds tables per the migration file’s schema, execute the below command.
python manage.py migrate
Read: How to Parse CSV in Python Django
Django CRUD with Bootstrap Template
Now, we have to work on the front end. For this, we have to create templates for each defined view. So, create folder templates with a subfolder named on the app.
In our case, the folder name is templates\MyApp.
Then, open the settings.py file, and update the DIRS to refer to the Templates folder’s location.
In Django, each class-based generic view, automatically renders out a template, if it is created on the default template name format.
The default template format for each view is given below. Make sure of one thing the template files are located inside the folder with the app name inside the template folder.
Class-based Generic View | Template View Name |
---|---|
Create View | modelname_form.html |
List View | modelname_list.html |
Detail View | modelname_detail.html |
Update View | modelname_{template_name_suffix}_form.html |
Delete View | modelname_confirm_delete.html |
Before, creating template files for each view first, we will first build the base.html file inside the templates folder, which will include the bootstrap code that we will need in each view.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title>Registration</title>
</head>
<body>
<div class="container">
<div class="pb-2 bg-info">
<div class="p-2 pl-3 pr-3">
{% block content %}
{% endblock content %}
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"
integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"
integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
- Due to the reusability feature of Django, we create the base.html file, which contains the bootstrap coding that we desire in each template
- Firstly, in order to load our CSS, we place a link of it in the header of our page before any other stylesheets.
- Next, we specify the div class, which defines each template’s padding, margin, and background color.
- Then, we insert {%block content%} into our HTML to specify that the contents of this block may be overridden by a child class and should be replaced by whatever is contained in the corresponding tags of the child class.
- The functionality of several of our components depends on JavaScript and to enable the following scripts, we add them before the closing body tag.
Now, create the HTML file for the CreateView. In our case, the file name is
templates\MyApp\memberregistration_form.html. Add the following code to the file.
{% extends "base.html" %}
{% block content %}
<div class=container>
<h5 align="center">Welcome to Fitness Club!!! Register your Gym Members.</h5>
<hr>
<form method="POST" class="post-form">
{% csrf_token %}
{% load crispy_forms_tags %}
{{ form.name|as_crispy_field }}
{{ form.gender|as_crispy_field }}
{{ form.date_of_birth|as_crispy_field }}
{{ form.personal_address|as_crispy_field }}
<div class="row">
<div class="col">
{{ form.city|as_crispy_field }}
</div>
<div class="col">
{{ form.state|as_crispy_field }}
</div>
</div>
{{ form.email|as_crispy_field }}
{{ form.weight|as_crispy_field }}
<input type="submit" class="btn btn-success" value="Submit Button">   <a href="/listmembers"
class="text-white">Move to list--></a>
</div>
{% endblock content %}
- In this template will inherit all of the code from our base template and replace the blocks set in the base template.
- Then, we must include the line {% extends ‘base.html’%} at the start of our code in order to inherit from the base template.
- The block is then replaced with the form we constructed using the form tag and POST method. We also utilize the csrf_token to safeguard the form against online threats.
- Then, we load the crispy_form_tag and call each form field separately using the {{form.name_of_field|as_crispy_field}} tag in order to style the Django form using bootstrap.
Now, create the HTML file for the ListView. In our case, the file name is
templates\MyApp\memberregistration_list.html. Add the following code to the file.
{% extends "base.html" %}
{% block content %}
<div class="container">
<h5 align="center">Welcome to Fitness Club!!! View your all Gym Members. </h5>
<hr>
<ol type="1">
{% for object in object_list %}
<li>
<a href="/memberdetails/{{object.id}}" class="text-white">{{object.name}}</a>
</li>
<hr>
{% empty %}
<li>
No member register yet.
</li>
{% endfor %}
</ul>
<a href="/" class="text-white"><--Back to Registration Form</a>
</div>
{% endblock content %}
- We must include the line {% extends ‘base.html’%} at the start of our code in order to inherit from the base template.
- The block is then replaced with the block of for loop which iterates over the object_list and displays the name as a hyperlink using a href tag in the ordered list.
- We also call the Django empty tag; which will work if object_list is empty and prints the message.
Now, create the HTML file for DetailView. In our case, the file name is
templates\MyApp\memberregistration_detail.html. Add the following code to the file.
{% extends "base.html" %}
{% block content %}
<div class="container">
<h5 align="center">Welcome to Fitness Club!!! View your Gym Member complete detail.</h5>
<hr>
<table class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Gender</th>
<th scope="col">Date of Birth</th>
<th scope="col">Personal Address</th>
<th scope="col">City</th>
<th scope="col">State</th>
<th scope="col">Email</th>
<th scope="col">Weight</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{object.name}}</td>
<td>{{object.gender}}</td>
<td>{{object.date_of_birth}}</td>
<td>{{object.personal_address}}</td>
<td>{{object.city}}</td>
<td>{{object.state}}</td>
<td>{{object.email}}</td>
<td>{{object.weight}}</td>
<td><a class="btn btn-warning" href="/{{object.pk}}/updatemember/" role="button">Update</a><a
class="btn btn-danger" href="/{{object.pk}}/deletemember" role="button">Delete</a>
</td>
</tr>
</tbody>
</table>
<a href="/listmembers" class="text-white"><--Back to list</a>
</div>
{% endblock content %}
- We must include the line {% extends ‘base.html’%} at the start of our code in order to inherit from the base template.
- The block is then replaced with the block of the table which prints the whole detail of the member in the table format.
- Next, we add buttons as a hyperlink that move us to the Update or Delete view.
Now, create the HTML file for the UpdateView. In our case, the file name templates\MyApp\memberregistration_update_form.html. Add the following code to the file.
{% extends "base.html" %}
{% block content %}
<div class="container">
<h5 align="center">Welcome to Fitness Club!!! Update your Gym Member details.</h5>
<hr>
<form method="POST" class="post-form">
{% csrf_token %}
{% load crispy_forms_tags %}
{{ form.personal_address|as_crispy_field }}
{{ form.city|as_crispy_field }}
{{ form.state|as_crispy_field }}
{{ form.email|as_crispy_field }}
{{ form.weight|as_crispy_field }}
<button type="submit" class="btn btn-warning">Update</button>
</form>
</div>
{% endblock content %}
- We must include the line {% extends ‘base.html’%} at the start of our code in order to inherit from the base template.
- The block is then replaced with the form we constructed using the form tag and POST method. We also utilize the csrf_token to safeguard the form against online threats.
- Then, we load the crispy_form_tag and call some specific form field separately that we want to update using the {{form.name_of_field|as_crispy_field}} tag in order to style the Django form using bootstrap.
- Last, we add the Update button to update the member details and on the successful updation, it will render back to the list view.
Now, create the HTML file for the DeleteView. In our case, the file name is
templates\MyApp\memberregistration_confirm_delete.html. Add the following code to the file.
{% extends "base.html" %}
{% block content %}
<div class="container">
<h5 align="center">Welcome to Fitness Club!!!Delete your Gym Member.</h5>
<hr>
<form method="post">
{% csrf_token %}
<p>Are you sure you want to delete "{{object.name}}"?</p>
<button type="submit" class="btn btn-danger">Delete</button>
</div>
{% endblock content %}
- We must include the line {% extends ‘base.html’%} at the start of our code in order to inherit from the base template.
- The block is then replaced with the code that will use to delete the member.
- Last, we add the Delete button, which will delete the member and render it back to the list view.
Read: How to add dropdown navbar in Django
View to perform CRUD using class-based generic views
Let’s first get the overview of the class-based generic views that we are going to use to perform CRUD operations.
- CreateView: To add new entries to a table in the database.
- RetrieveView: Read, Retrieve, Search, or View existing entries as follow
- ListView: In the list form.
- DetailView: Particular entry in detail.
- UpdateView: Update or Edit existing entries in a table in the database.
- DeleteView: Delete, Deactivate, or Remove existing entries in a table in the database.
To create the main logic for the CRUD operations with bootstrap, we open the views.py file and add the below-given code.
from .models import MemberRegistration
from django.views.generic.edit import CreateView,UpdateView,DeleteView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
# Create your views here.
# Create View
class MemberCreate(CreateView):
model = MemberRegistration
fields = "__all__"
success_url = '/listmembers'
# List View
class MemberList(ListView):
model = MemberRegistration
queryset = MemberRegistration.objects.all()
# Detail View
class MemberDetail(DetailView):
model = MemberRegistration
# Update View
class MemberUpdate(UpdateView):
model = MemberRegistration
fields = ['personal_address','city','state','email','weight']
template_name_suffix = '_update_form'
success_url = "/listmembers"
# Delete View
class MemberDelete(DeleteView):
model = MemberRegistration
success_url = "/listmembers"
- CreateView is a view used to create a database table object.
- Here, we create a subclass named MemberCreate, then we extend it with the existing view named CreateView.
- After this, we define the model MemberRegistraion and fields __all__ by using which, create view i.e database is created.
- We also override the success_url attribute, which redirects to the listmembers URL path on successful submission.
- ListView is a view that allows multiple instances of a table to be displayed.
- Here, we create a subclass named MemberList, then we extend it with the existing view named ListView.
- After this, we define the model MemberRegistration by using which name of the member of the model displayed.
- A view that displays just one instance of a table from a database is referred to as a DetailView.
- Here, we create a subclass named MemberDetail, then we extend it with an existing view named DetailView.
- After this, we define the model MemberRegistration by using which the detail of the member displayed.
- UpdateView is a view used to update some information to a specific instance of a table in the database.
- Here, we create a subclass named MemberUpdate, then we extend it with the existing view named UpdateView.
- After this, we define the model MemberRegistration and fields personal_address, city, state, email, and weight by using which update view is created.
- Then, override the success_url attribute on it, which redirects to the listmembers URL path on successful submission.
- We also override the template_name_suffix attribute on it and define it as _update_form, which means that it will look for the app_name/modelname_update_form.html template instead of the app_name/modelname_form.html template.
- A view that deletes a specific instance of a table from the database is referred to as a DeleteView.
- Here, we create a subclass named MemberDelete, then we extend it with the existing view named DeleteView.
- After this, we define the model MemberRegistration and fields __all__ by using which delete view is created.
- Then, override the success_url attribute on it, which redirects to the listmembers URL path on successful deletion.
We must map the view with the URL in order to call it, thus we must create a file called urls.py in the app directory. Include the code below in it.
from django.urls import path
from .views import MemberCreate, MemberList, MemberDetail, MemberUpdate, MemberDelete
urlpatterns = [
path('',MemberCreate.as_view(),name='MemberCreate'),
path('listmembers/',MemberList.as_view(),name='MemberList'), path('memberdetails/<pk>',MemberDetail.as_view(),name='MemberDetail'), path('<pk>/updatemember/',MemberUpdate.as_view(),name='MemberUpdate'), path('<pk>/deletemember/',MemberDelete.as_view(),name='MemberDelete'),
]
- Here, we add MemberCreate, MemberList, MemberDetail, MemberUpdate, and MemberDelete classes with the as_view() method.
Execute Django Project
To launch a development server type the below-given command in the terminal.
python manage.py runserver
It will open, the page having the form used for entering the details of gym members.
On successful submission, it will redirect to a page that has a list of gym members.
Now, click on the name of a specific gym member whose details we want to see. It will successfully show us detail in the table format with two actions Update and Delete.
Suppose, a gym member who joined the gym for weight loss has lost some kgs of weight, and now we want to update his/her data in our Gym Management System.
So, we click on the Update button it will show us some fields that we can update. Here we update the weight and click on the Update button.
On successful updation, it will redirect to a page that has a list of gym members. And by clicking on a specific member we can view its updated details.
Suppose, one of the gym member left the gym and now we want to delete it from our Gym Management System. Click on the specific gym member who left the gym and we will redirect to the detail page with two actions.
Now, click on the Delete button, It will show us the confirmation message with the name of the member and the Delete button. If you surely want to delete this member, click on Delete, and it successfully deleted the member.
Note: If you want to move to the member list page instead of entering the details of a new member, click on the link that specifies the URL of the page, and if you want to move back to the member-entering page click on the link that specifies the URL of the page.
Read: How to create a function-based view in Django
View data from the Django admin interface
The data is also saved in the Django admin interface. If you want to view it first we have to create a super user using the below command.
python manage.py createsuperuser
Now, click on Gym registration under MYAPP you can successfully view entered records.
This is how we can perform Django CRUD operation with Bootstrap Template.
Read: How to use CKEditor in Django?
Download Django CRUD operation with bootstrap Template complete code
Conclusion
With this, we have successfully learned to perform CRUD operations with the bootstrap template. We have also learned to create class-based generic views for performing CRUD operations and the use of the crispy form tag for creating bootstrap templates with less number of coding lines.
Additionally, we have also covered the following topics.
- Why use Django Crispy Forms for bootstrap
- How to perform CRUD operation using class-based generic view
- How to perform CRUD operation with bootstrap
- How to build gym registration system using class-based generic view and bootstrap
- How to use Django Crispy Forms to implement bootstrap
- How to use various controls like textbox, radio button, select field, and help_text in Django
You may also like to read the following Python Django tutorials.
- How to add Google reCAPTCHA to Django Form
- How to create form with Django Crispy Forms
- How to create Email sender app in Django?
- Django contact form with class based views
- Create Contact Form with Django and SQLite
- How to create an API in Python Django
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.