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 manage.py 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 settings.py file. You can create an environment variable and access it from the settings.py file

$DB_PASS='mypassword'
$export DB_PASS

Edit the settings.py 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 manage.py inspectdb > employee_app/models.py

Part of the generated models.py file

Make Migrations and Migrate your Models

$python manage.py makemigrations$python manage.py migrate

Add the employee_app and restframework in settings.py 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

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

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

https://github.com/chrysmur/getting_started_with_Django_Mysql_and_react/blob/master/backend/employee_app/serializers.py

Views

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 views.py 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.

https://github.com/chrysmur/getting_started_with_Django_Mysql_and_react/blob/master/backend/employee_app/views.py

URLs

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 urls.py files in the project directory

https://github.com/chrysmur/getting_started_with_Django_Mysql_and_react/blob/master/backend/backend/urls.py

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

https://github.com/chrysmur/getting_started_with_Django_Mysql_and_react/blob/master/backend/employee_app/admin.py

Testing our App

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

From backend directory, run:

$python manage.py runserver 0.0.0.0:8080

Open your browser and enter the url http://127.0.0.1:8080/api

Expected Results

HTTP 200 OKAllow: GET, HEAD, OPTIONSContent-Type: application/jsonVary: Accept{    "employees": "http://127.0.0.1:8080/api/employees/",    "departments": "http://127.0.0.1:8080/api/departments/",    "deptemp": "http://127.0.0.1:8080/api/deptemp/",    "deptmanager": "http://127.0.0.1:8080/api/deptmanager/",    "salaries": "http://127.0.0.1:8080/api/salaries/",    "titles": "http://127.0.0.1:8080/api/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://127.0.0.1:8080/api/salaries/")

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 settings.py 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

INSTALLED_APPS = (
...
'corsheaders',
...
)
MIDDLEWARE = [ # Or MIDDLEWARE_CLASSES on Django < 1.10
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ORIGIN_WHITELIST = [
"http://localhost:3000
)

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