How to connect Django application to MySQL Database

After completing your django web application development on local host, it’s time to take it to production. You may need to switch to a more stable database as SQLite database is not recommended for production. For this to happen, you will need to adjust your code to have your web application integrated with the MySQL database.

Procedure.

  1. Install the required dependancy.

pip install pymysql

2. Go to your settings.py :: This is found in the folder that was generated on running > django-admin startproject appname:: inside the appname/root folder for your project, there is another folder named appname, where the settings.py is.

By default; the database configuration is:

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

3. To connect your application to MySQL database, first, create the database, see the guide on how to create a MySQL database on Cpanel up to step 5 https://truehost.com/support/knowledge-base/how-to-upload-and-configure-mysql-database-into-cpanel/: and replace the database code above by the one below:

DATABASES = {
‘default’: {
‘ENGINE’: ‘django.db.backends.mysql’,
‘NAME’: ‘DBNAME’,
‘USER’: ‘DBUSER’,
‘PASSWORD’: ‘DBPASSWORD’,
‘HOST’: ‘localhost’,
‘PORT’: ‘3306’,
‘OPTIONS’: {
‘init_command’: “SET sql_mode=’STRICT_TRANS_TABLES'”
}
}
}

Replace the DBNAME, DBUSER and DBPASSWORD with the details you used in setting up the database.

4. Under the same folder with the settings.py file, click and edit the __init__.py file and paste the code below and save;

import pymysql

pymysql.install_as_MySQLdb()

That’s all that is required to configure the MySQL database. After the above procedure, continue to do the migrations and other setups. See how to Deploy Django application on shared hosting : https://truehost.com/support/knowledge-base/how-to-deploy-django-web-application-on-shared-hosting-cpanel/

Was this article helpful?

Related Articles

Leave A Comment?