Django MySQL Database Tutorial

With this tutorial, you will have a Django project connected and fully working with a MySQL database in just a few minutes.

 

Install MySQL

The first step is to install MySQL on your machine. If you are using Linux/Ubuntu use the following commands to update the system then install the mysql-server package:

 

sudo apt update
sudo apt install mysql-server

 

To install MySQL on macOS, use the Brew package manager like this:

 

brew install mysql

 

Then enable it like this:

 

brew services start mysql

 

The final step is to secure the MySQL installation:

 

mysql_secure_installation

 

Follow the instructions and select the level of security you want.

 

Note – the above step is optional but highly recommended.

 

Install Mysql Python Client

Python needs the mysqlclient package so that it can communicate with your MySQL server. Make sure you are using the same version of Python Django is using and use the pip package manager to install it like this:

 

pip install mysqlclient

 

Configure a MySQL Database, User and Grant Privileges

Now login to MySQL as the root user like this, supplying the password created earlier when prompted:

 

mysql -u root -p

 

Now create a database with the following command, replacing exampledb with the name of the database to create:

 

CREATE DATABASE exampledb DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

 

Now create a new MySQL user with the following command, replacing newuser and user_password:

 

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'user_password';

 

Next, grant all privileges for the new user to the new database:

 

GRANT ALL PRIVILEGES ON database_name.* TO 'database_user'@'localhost';

 

Configure Django to Connect to MySQL

Open the settings.py file in the root of your project, locate to the DATABASES variable, comment it out and add the following code replacing the settings with the ones you just configured:

 

DATABASES = {
   'default': {
       'ENGINE': 'django.db.backends.mysql',
       'NAME': 'you_db',
       'HOST': '127.0.0.1',
       'PORT': '3306',
       'USER': 'your_user',
       'PASSWORD': 'password',
   }
}

 

Migrate Django Tables

The next step is to migrate your Django tables to the MySQL database. cd to the root of your project and run the following command:

 

python manage.py migrate

 

Create Django Admin Superuser

The final step is to create a new superuser so that you can login to the Django admin panel

 

python manage.py createsuperuser

 

That's it! Your Django project is now running with an SQL database.

django mysql