Getting Started with Django and MySQL Backend

This is a beginner’s guide to Django Framework for backend Development with MySQL, DjangoRestFramework that can be integrated with any frontend. We are creating a simple system that exposes database data an API that we create using DRF.

Image for post
Image for post
Illustration of the concept

Django Installation and Python Virtual Environment

You want to create a development environment which you can control. Virtual Environments help you install all packages that you need for a specific development task without necessarily affecting your base system. It also helps you manage dependencies when deploying the application.

--Virtual Environment
$sudo apt install python3-venv python3-pip
$python3 -m venv “/path to your location folder”--activate the virtual environment$ source <location folder>/bin/activate--install latest django version$pip install django$pip install djangorestframework---start django project and app.$django-admin startproject backend$ cd backend$python startapp employee_app

Django project is the main project directory, and applications go inside the project folder. You can have many applications in one project. In our case we call the project ‘backend’ and the first app ‘employee_app’

Connecting Django to MySQL

Django manages database using models. Django models are mappings of the database, which helps you interact with the database even with little knowledge of SQL syntax. However, if you have a database that has existing data, Django helps you inspect the database and automatically generate the corresponding models for you. I have used this SQL file to create my Database.

--Create SQL database in the projec's root directory. I am running my Database as root user, you can use  different user.$mysql -u 'root' <  "employees.sql" -p

Change the Django default Database from sqlite3 to MySQL

It is recommended that you avoid typing the password in the file. You can create an environment variable and access it from the file

$export DB_PASS

Edit the file

Creating the Database Models using InspectDB

If you have a database that has existing data, Django helps you inspect the database and automatically generate the corresponding models for you.

$pip install mysqlclient
$python inspectdb > employee_app/

Part of the generated file

Make Migrations and Migrate your Models

$python makemigrations$python migrate

Add the employee_app and restframework in under installed apps

INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'employees_app',    'rest_framework',]

Handling Django Rest API


Serializers allows the conversion of complex data types such as querysets to native python datatypes.

Create “” in the employee_app. Create a Serializer for each model in the file. djangorestframework has several types of serializers. In this case with are inheriting the ModelSerializer type and returning all fields of the tables.


Views helps the user to interact with the database using viewsets. The idea is to create a query that fetches data from the database using the models, then pass the data through the Serializer before exposing it to the user.

In each view, we define the serializer we are using, and the create a queryset, that specifies the type and amount of content we want to get

Modify the file in the employee_app. I am limiting my queries to a few rows because the database contains many entries.You can create more advanced viewsets.


We will use the rest_framework’s routers to dynamically create urls for our views. all we need to do is register the views

Edit the files in the project directory

We need to register the models in the admin site. Open in the project directory.

Testing our App

Having saved these changes, we run our server and test the apis

From backend directory, run:

$python runserver

Open your browser and enter the url

Expected Results

HTTP 200 OKAllow: GET, HEAD, OPTIONSContent-Type: application/jsonVary: Accept{    "employees": "",    "departments": "",    "deptemp": "",    "deptmanager": "",    "salaries": "",    "titles": ""}

Click on any of the links and you should see some data from our sql database displayed in JSON format.

Salaries Api List (")

HTTP 200 OKAllow: GET, POST, HEAD, OPTIONSContent-Type: application/jsonVary: Accept[{    "emp_no": 10001,    "salary": 60117,    "from_date": "1986-06-26",    "to_date": "1987-06-26"},{    "emp_no": 10001,    "salary": 62102,    "from_date": "1987-06-26",    "to_date": "1988-06-25"},{    "emp_no": 10001,    "salary": 66074,    "from_date": "1988-06-25",    "to_date": "1989-06-25"},

We now have a working backend API using Django and MySQL. Next we will create a React Application that display this information in a browser.

Cross Origin Resource Sharing (CORS)

Accessing Django API from a react frontend or any other framework is by default disabled. To allow for this sharing install corsheader in django from pip.

$pip install django-cors-headers

Add corsheaders in the installed apps in and add a middleware to listen on the responses. Ensure that corsheaders.middleware is the first on the list.

Next create a list of allowed hosts to connect to this server by creating a CORS_ORIGIN_WHITELIST. I have allowed the default React_app url. If you want to allow all hosts, set CORS_ORIGIN_ALLOW_ALL=True


Full Code here

Written by

Python Developer, SQL, React, Data science and ML

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store