MDB 5 Django Integration
MDB 5 Django integration
This article shows you how to integrate Django backend application with MDB Standard UI Kit.
This guide will walk you through steps necessary to include MDB package in your Django project and to add some basic setup for your project.
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 we can go through all the steps together. For this tutorial we'll be using MySQL database.
Step 1
Creating a MySQL database
In order to create a new database you need to run the following command
mdb database init
- Choose
mysql8
- Create a new user
- Provide username, password, database name and description.
CLI will display your username, password, database name and connections string. Now you can go to phpMyAdmin where you will be able to handle the administration of the MySQL database.
Note Note: Your final username and database name may differ from your inputs. MDB GO may add some characters to randomize username and database name.
Important Do not close your terminal window until you save your credentials somewhere. This is the only time we will show you your database password. If you won't save it you'll loose it.
Step 2
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 3
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 developement application.
pip install djangorestframework
pip install django-cors-headers
Step 4
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 as exampleApp
but you can go with whatever you want.
django-admin startproject exampleApp
Step 5
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 the code.
cd exampleApp
python3 manage.py startapp toDoApp
cd exampleApp
py manage.py startapp toDoApp
Step 6
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 aswell.
...
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 7
Now we have to create a model needed for our app. We need id
field which value will be autofilled. We also need name
and desc
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 8
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 database and manipulate its contents.
pip install mysqlclient
Step 9
Go to settings.py
, go to 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 passowrd]',
'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
Check toDoApp/migrations/0001_initial.py
if everything is correct and then migrate the data. Now you can see the changes after logging 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
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 toDoApp
directory create templates
directory 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
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 base project directory type the following command in the terminal.
It will change directory to toDoApp
and initialize MDB CLI. From the list of starters select mdb5-free-standard
.
cd toDoApp
mdb init
Step 2
Change name of created folder from mdb5-free-standard
to static
.
Step 3
At the beginning of index.html
file add {% load static %}
and in the head
import static CSS files.
{% load static %}
<link href="{% static 'css/mdb.min.css' %}" rel="stylesheet" type="text/css"/>
Step 4
At the end of body
tag in index.html
file import static JS files.
<script src="{% static 'js/mdb.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 capabilities of Django used with MDB package by creating example To Do App.
Step 1
Change content of the body
tag in index.html
file to content of the snippet below but don't remove 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-toggle="modal" data-mdb-target="#TaskModal" id="addTaskButton">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">
<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">
<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">
Close
</button>
<button type="submit" class="btn btn-primary" id="confirmButton">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-toggle="modal" 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">
<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 simple To Do app with connected to 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 the created app, with which we can build basic views very quickly.
Info: If you want to use customized version of MDB UI KIT with your own project, you need to use
bundler like webpack
and modify source code. To learn about how to include and bundle the MDB package in
your project using Webpack visit
this page in MDB documentation.
Views and Layouts:
We have successfully integrated the backend with the MDB package and can send basic requests to backend Django application.