[Django Tutorial] Connect MySQL Database in Django Framework

If you are looking forward to connect your MySQL database with python code that check the following guide:

In order to connect your MySQL Database in Django Framework, you should do the following:

  1. Install MySQL package
  2. Configure your settings.py
  3. Make Migrations

Install MySQL Package

First install MySQL via pip from your terminal with the following command:

pip install mysql

We will be using django.db.backends.mysql mysql as our backend which means installing mysql is setting a bridge to communicate between python and mysql.

Configure settings.py

After successful installation of mysql package we need to write the database configuration which confirms that our project uses mysql database as a backend. In your settings.py search for the DATABASES key and add the followilg properties:

DATABASES = {
    'default': {
        'NAME': 'db_name',
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'demo',
        'PASSWORD': 'demo',
        'OPTIONS': {
            'autocommit': True,
        },
    },
}

Keep your prederred database name, username and password and save it.

Make Migrations

Finally we are set to connect to the mysql database. One thing that we need to understand here is that, we are using standard python queries to communicate and process the tables. After creating that database in your mysql server, run the following command first:

python manage.py makemigrations
python manage.py migrate

Once the mirgation is successful browse for the tables on your mysql database:

mysql> show tables;
+----------------------------+
| Tables_in_mdi              |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
10 rows in set (0.00 sec)

You will see the following tables. So from now on if you will createsuperuser or modify information about users, user groups and sessions it will be stored in this database.