Django Integration
How to use Bootstrap 5 with Django - free starter
This guide will provide you with a free template for a Django application, with MySQL database and Bootstrap 5 front-end.
Prerequisites
Before starting the project make sure to install the following utilities:
Creating a new Django application
Let's create a fresh Django application so that we can go through all the steps together. For this tutorial we'll be using MySQL database.
Note: Depending on your OS you may need to use different commands. Copy the commands appropriate for your operating system.
Step 1
Creating Django API.
Install Django on your computer.
Note: If you are getting errors, try typing these commands in cmd instead of in the VSC terminal or check your Python environment settings.
python3 -m pip install django
py -m pip install Django
Step 2
Now we have to install the necessary modules that are needed for the Django backend to work properly.
To create Django web API we will need Django Rest Framework. We should also install module that will be responsible for handling CORS issues in our development application.
pip install djangorestframework
pip install django-cors-headers
Step 3
Navigate to your project directory, i.e. my-django-app
.
Let's create a Django project by typing the code below. We are naming our project exampleApp
but you can go with whatever you want.
django-admin startproject exampleApp
Step 4
Now that we have the project installed, let's create a new app in which we will put all the functions we will need. Navigate to the newly created directory with django project and enter the following code.
cd exampleApp
python3 manage.py startapp toDoApp
cd exampleApp
py manage.py startapp toDoApp
Step 5
Register the app and new modules in settings.py
. If you are not sure about the name of your app, go
to toDoApp/apps.py
and copy the class name. We have to register corsheaders
in middlware
section as well.
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'toDoApp.apps.TodoappConfig'
]
CORS_ORIGIN_ALLOW_ALL = True
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
...
Step 6
Now we have to create a model needed for our app. We need an id
field, its value will be autofilled. We also need name
and desc
fields with the max length set as below.
from django.db import models
# Create your models here.
class Tasks(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
desc = models.CharField(max_length=255)
Step 7
Django requires installing mysqlclient
in version 1.4.0
or higher so it can work with
MySQL properly. Without it, you wouldn't be able to communicate with a database and manipulate its contents.
pip install mysqlclient
Step 8
Creating a MySQL database.
In order to create a new database you need to run the following command.
Note: If you don't have MDB CLI installed yet, you can do it with NPM: npm install -g mdb-cli
.
Now log in with your MDB account, type: mdb login
.
If you don't have account yet you can create one using mdb register
command.
mdb database init -db mysql8
- Create a new user
- Provide username, password, database name and description.
CLI will display your username, password, database name and connections string. You will need this data in the next step. Now you can go to phpMyAdmin where you will be able to handle the administration of the MySQL database.
Note: the password must contain at least one uppercase letter, one lowercase letter, one number, one special symbol and have minimum length of 8.
Step 9
In the settings.py
, go to the DATABASES
section, and add the database connection details. Change the values between brackets
for the ones you got after creating a new MySQL Database from our starter.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '[Your database name]',
'USER': '[Your user name]',
'PASSWORD': '[Your password]',
'HOST': 'mysql.db.mdbgo.com',
'PORT': '3306'
}
}
Step 10
Make migration with our models to the database.
python3 manage.py makemigrations toDoApp
py manage.py makemigrations toDoApp
Step 11
In toDoApp/migrations/0001_initial.py
file check if everything is correct and then migrate the data. Now you can see the changes after logging in to https://phpmyadmin.mdbgo.com/
python3 manage.py migrate toDoApp
py manage.py migrate toDoApp
Step 12
Open views.py
and start working on API methods we'll be using. We are going to create GET
and POST
endpoints that will support the functionality of the front-end app.
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from toDoApp.models import Tasks
# Create your views here.
@csrf_exempt
def TaskList(request):
if request.method == 'GET':
tasks = Tasks.objects.all()
context = {'tasks':tasks}
return render(request, 'index.html', context)
if request.method == 'POST':
id = request.POST.get('id')
if id == '':
task = Tasks.objects.create(
name = request.POST.get('name'),
desc = request.POST.get('desc')
)
task.save()
return redirect('tasks')
else:
task = Tasks.objects.get(id=id)
task.name = request.POST.get('name')
task.desc = request.POST.get('desc')
task.save()
return redirect('tasks')
def TaskDelete(request, pk):
task = Tasks.objects.get(id=pk)
task.delete()
return redirect('tasks')
Step 13
In the toDoApp
directory create a new urls.py
file where we will define routes for our API methods.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('toDoApp.urls'))
]
Step 14
Add new path to urls.py
in the main project directory.
from django.urls import path
from toDoApp import views
urlpatterns = [
path('', views.TaskList, name='tasks'),
path('<str:pk>', views.TaskDelete, name="delete"),
]
Step 15
In the toDoApp
directory create a templates
folder and create file index.html
inside it. Paste there code from the snippet below as placeholder content.
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Material Design for Bootstrap</title>
<!-- Font Awesome -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
</head>
<body>
<div class="container py-4 px-3 mx-auto">
<h1>Hello, MDB and Django!</h1>
<button class="btn btn-primary">Primary button</button>
</div>
</body>
</html>
Step 16
Now we can make migrations, restart the server and go to http://127.0.0.1:8000/
. You should see
an unstyled placeholder page there.
python3 manage.py makemigrations
python3 manage.py migrate
python3 manage.py runserver
py manage.py makemigrations
py manage.py migrate
py manage.py runserver
Install MDB
In this section we will add MDB styles and JavaScript files to the example page.
Step 1
From the base project directory type the following command in the terminal.
It will change the directory to toDoApp/static
and initialize MDB CLI. From the list of starters select Standard
.
Note: If you don't have MDB CLI installed yet, you can do it with NPM: npm install -g mdb-cli
.
Now log in with your MDB account, type: mdb login
.
If you don't have account yet you can create one using mdb register
command.
cd toDoApp
mkdir static
cd static
mdb frontend init mdb5-free-standard
Step 2
At the beginning of the index.html
file add {% load static %}
and in the head
import static CSS files.
{% load static %}
<link href="{% static 'mdb5-free-standard/css/mdb.min.css' %}" rel="stylesheet" type="text/css"/>
Step 3
At the end of the body
tag in the index.html
file import static JS files.
<script src="{% static 'mdb5-free-standard/js/mdb.umd.min.js' %}"></script>
Now you're done
With MDB's CSS and JS fully loaded, after restarting the server your example page should work and you should see MDB styles applied to its content.
To Do App with MDB
In this section, we will present the capabilities of Django used with the MDB package by creating an example To Do App.
Step 1
Change the content of the body
tag in the index.html
file to content of the snippet below
but don't remove the script
tag that imports JavaScript files.
<div class="container mt-5">
<!-- Button trigger modal -->
<div class="row pt-5">
<div class="col text-center">
<button class="btn btn-primary" data-mdb-modal-init data-mdb-target="#TaskModal" id="addTaskButton" data-mdb-ripple-init>Add task</button>
</div>
</div>
<!-- Modal Add -->
<div class="modal top fade" id="TaskModal" tabindex="-1" aria-labelledby="TaskModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="taskModalLabel">Add task</h5>
<button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
</div>
<form action="/" method="POST" id="taskForm">
<div class="modal-body">
{% csrf_token %}
<div class="form-outline mb-4" data-mdb-input-init>
<input name='name' type="text" id="editNameInput" class="form-control"/>
<label class="form-label" for="editNameInput">Name</label>
</div>
<div class="form-outline mb-4" data-mdb-input-init>
<input name="desc" type="text" id="editDescInput" class="form-control">
<label class="form-label" for="editDescInput">Description</label>
</div>
<input name="id" type="hidden" id="taskId" >
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-mdb-dismiss="modal" data-mdb-ripple-init>
Close
</button>
<button type="submit" class="btn btn-primary" id="confirmButton" data-mdb-ripple-init>Confirm</button>
</div>
</form>
</div>
</div>
</div>
<!-- List of tasks -->
<div class="row mt-3 p-5">
<div class="col d-flex justify-content-center align-items-center">
<ul class="list-group list-group-light" style="min-width: 22rem;">
{% for task in tasks %}
<li class="list-group-item d-flex justify-content-between align-items-center gap-5" id="{{task.id}}">
<div>
<div class="fw-bold name">{{task.name}}</div>
<div class="fw-bold desc">{{task.desc}}</div>
</div>
<div class="d-flex align-items-center">
<a class="btn btn-primary btn-floating me-2" data-mdb-modal-init data-mdb-ripple-init data-mdb-target="#TaskModal" onclick="setModalValues('{{task.id}}')">
<span class="fas fa-pen text-white"></span>
</a>
<form action="{% url 'delete' task.id %}" class="my-0">
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-floating" data-mdb-ripple-init>
<span class="fas fa-trash text-white" title="delete"></span>
</button>
</form>
</div>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
Step 2
At the end of the body
tag in index.html
add code from the snippet below.
<script>
const editNameInput = document.getElementById('editNameInput');
const editDescInput = document.getElementById('editDescInput');
const taskId = document.getElementById('taskId');
const taskForm = document.getElementById('taskForm');
const taskModalLabel = document.getElementById('taskModalLabel');
function setModalValues(id) {
const task = document.getElementById(id)
editNameInput.value = task.querySelector('.name').innerText;
editDescInput.value = task.querySelector('.desc').innerText;
taskId.value = id;
taskModalLabel.innerText = 'Edit task';
}
const addTaskButton = document.querySelector('#addTaskButton');
addTaskButton.addEventListener('click', () => {
taskForm.reset();
taskModalLabel.innerText = 'Add task';
})
</script>
After refreshing the page, you should see a simple To Do app connected to a MySQL database.
Optimization
If you want to further optimize your application please visit:
Backend features
Django:
This example was created with the use of Django. Our app is connected to MySQL database and is ready to receive get
and post
requests.
MDB CLI:
The database in this example was created using MDB CLI with Graphical User Interface available under phpmyadmin.mdbgo.com
Frontend features
MDB UI KIT:
We have successfully added MDB UI Kit to the created app, with which we can build basic views very quickly.
Views and Layouts:
We have successfully integrated the backend with the MDB package and can send basic requests to backend Django application.