27 – HOW TO CONFIGURE DJANGO TO USE A MYSQL DATABASE

Spread the love

MySQL server is one of the most stable relational database system. It has been arround for long time and running behind a lot of website and applications. In this tutorial, i will work you how to setup django to use MySQL server as the data store for the application.

While we will be using MySQL on this tutorial, these steps should be similar to other relational database systems like PostgreSQL.

We will be installing MySQL workbench but it is not required to run Django. MySQL Workbench is only used to manage the database server by providing an easy Graphical User Interface (GUI).

Step 1: Installing MySQL Server, Workbench and some prerequisites

Install MYSQL database, MYSQL workbench, and some prerequisites to connect Django to the database.
sudo apt install mysql-server libmysqlclient-dev python-dev mysql-workbench
or use below command if you run an older version of ubuntu
sudo apt-get install mysql-server libmysqlclient-dev python-dev mysql-workbench
Enter the root password and confirm it when prompted

Step 2: Activating Virtualenv and installing mysqlclient

Navigate into the virtual environment, Activate the virtual environment and install mysqlclient and occasionally mysql-python
cd venv(where venv is the name of the virtual environment)
source bin/activate
pip install mysqlclient

Step 3: Creating a Database and Username

Open mysql workbench, create a database (schema) and username to be used to connect to the database.

I will use these parameters:
database name = stockmgmt
Username = myusername
Password = myPassword

Step 4: Configuring Django to use the database creating in step 3

In the application settings.py file, configure Django to use MYSQL Database instead of the SQLite file (the default).
in this example we are using the database, username, and password created in the above step:
database name = stockmgmt
Username = myusername
Password = myPassword

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'stockmgmt',
        'USER': 'myusername',
        'PASSWORD': 'myPassword',
    }
}

Step 5: Creating tables in the newly created database

Django allows us to easily create tables in the database with a simple script (python manage.py migrate)

Do migrate for Django to create the application tables to the newly configured database.

You might want to delete all the files in the migration folder except __init__.py if you want to are do a clean setup. Watch the video for more explanation.
./manage.py migrate
./manage.py runserver


Spread the love

About the author

arbadjie

Hi, I'm Abdourahman Badjie, an aspiring developer with obsession for anything coding and networking. This blog is dedicated to helping people learn to develop web applications using django framework.

View all posts

13 Comments

Leave a Reply to Theoneste Cancel reply

Your email address will not be published. Required fields are marked *