Django App featured image

Creating a Django App with Database Connection: A Tutorial

Django is a free and open-source web framework built in Python. First published in 2005, Django incorporates the motto of “rapid development and clean, pragmatic design.” The framework, deployed on a web server, can quickly produce a web front-end with rich features, security, and scalability.

Any web app relies on databases for its content. Django, being a modern framework, supports a number of standard database programs, for example, PostgreSQL, SQLite, MySQL, etc. This guide will showcase how to connect a Django app to a database on MySQL.

Prerequisites

To follow this tutorial you need to meet certain pre-conditions before moving to Django and database connection:

Installing and Configuring Python 3

Django is written in Python. Running any Python app requires the Python binaries to be installed in the system. Ubuntu comes with Python installed by default. Here, we’ll be using Python 3. From the terminal, run the following commands. First, update the APT cache and upgrade (if available) all the installed packages:

Python 3 is directly available from the official Ubuntu package servers. The package python-is-python3  creates a python binary soft link to python3 for ease of use:

Next, verify if the installation was successful:

After that, we need pip. It’s the standard Python package manager. It’s responsible for managing additional Python libraries that are not part of the standard library. Note that we’re installing pip3 (for Python 3):

Lastly, we need some additional packages for a robust programming environment:

Installing and Configuring MySQL

This section will briefly demonstrate installing and configuring MySQL. It’s available from the default Ubuntu package repos:

If the installation was successful, then MySQL will start running in the background. Verify if it’s working properly:

Django App 1

The MySQL server is up and running. We can now safely transition to the development of our Django app.

Working with Django

  • Establishing the sample Django app

The groundwork of our web app requires the Django project skeleton. It contains all the necessary tools and libraries required to create a robust web app. First, we will create a dedicated directory for our Django app. It’s recommended to name the directory something meaningful and consistent with the app we’re about to build. In this demonstration, we will be naming it myDemoApp:

We need the Python venv module to create a virtual environment within the directory. Install the module using APT:

Then, navigate to the directory and establish a virtual environment. For clarity, we named the environment demoapp_env:

Next, activate the virtual environment by running the activate script:

Django App 2

We’ll now install Django inside this dedicated virtual environment. Pip will download and install some additional components:

Django is installed and ready to be used. Call the django-admin command to create a new Django project. Аfter that, give the app an appropriate name:

It will create a demo project with the necessary project files and directories in place:

Django App 3

The project skeleton is ready. Next, we need to configure it properly to accomplish our goal.

  • Editing Django project settings

All the configurations of the project are stored under the file settings.py. It’s located within the Django project directory. We’ll start by setting a proper time zone and list hosts that can connect to the Django app. Open the configuration file in a text editor:

Scroll down the script and find the entry TIME_ZONE. For demonstration, the time zone is set to America/New_York:

TIME_ZONE

For reference, the following command will print all the supported time zones in Linux:

Next, scroll to the entry ALLOWED_HOSTS. It controls which machine(s) can access the app. For demonstration, it only contains localhost:

Django App 4Then, save the file and close the editor. The next command will apply the changes:

python manageNow, we need to create an admin account for the web app. This account will be used to access the Django admin interface. Run the following command:

Django App 5It will ask for username, email, and password. The app is now ready to connect to the database.

MySQL Connection

  • Installing MySQL connectors and development libraries

To integrate MySQL into the Django app, we need some additional Python 3 libraries that will provide the necessary tools. We’ll be using the database connector mysqlclient. It’s a fork of MySQLdb.

Ensure that we have python3-dev installed:

We also need some additional Python and MySQL headers and libraries:

After the installation is complete, use pip to install the Python module mysqlclient. It may generate some error messages that can be ignored:

  • Configuring a dedicated database

The next step is configuring a dedicated database and database user for our Django app. Launch the MySQL shell as the root user:

To check all the currently available databases, run the following query:

Let’s create a dedicated database for our Django app. Give it an appropriate name that’s consistent with the project name:

Then, verify the creation:

Django App 6Now, create a dedicated MySQL user. We’ll configure this user as the owner of the database. The Django app will use this user’s credentials to work with the MySQL database:

Give the user demoapp_user full permission over the database demoapp_data:

To take the permission changes into effect, reload the MySQL grant tables:

Django App 7The database is now ready to be connected to the Django app.

  • Connecting the Database to the Django App

Finally, we’ll configure the Django app to use the database for data storage. Open the configuration script settings.py:

Scroll down to the entry DATABASES and enter the following code:

Django App 8Save the file and close the editor. The next step is to set the configuration file described in the code before. Use sudo to open the text file in the described location:

This configuration file will contain info about the Django-dedicated database and the user we created in the MySQL server. Add the following lines at the end of the file:

default-character-setTo take the changes into effect, we have to restart the MySQL server:

  • Testing MySQL connection

It is now time to verify if the MySQL connection is working properly. If the Django server runs without issue, then the connection is working fine. Otherwise, there is something wrong. First, apply all the changes made to the Django project:

python manageNow, move to the following project directory and start the Django server:

python manage.py runserverNext, try to access the server from a web browser:

server_ip_address

Voila! We’ve successfully landed on the Django success page. It also verifies that the MySQL connection is working properly. After the task is finished, you can safely exit the virtual environment:

Final Thoughts

In this guide, you’ve learned the basics of combining Django and MySQL together. We created a Django app and showcased how to connect it with a MySQL database. The magic lies within the Django configuration file settings.py. We also modified some basic settings like ALLOWED_HOSTS and TIME_ZONE. Django is incredibly flexible. Besides MySQL, it also supports other SQL servers like PostgreSQL, server engines like Nginx, etc.

You can also check out our guides on the best practices to install, configure, and work with Django:

Happy Computing!