How to Configure and Connect Django with MySQL Step by Step

Video thumbnail

We start from the fact that we already know how to work with Django in models, and the next step is the database; although Django uses SQLite by default, which is an excellent database, sometimes we need to use a more complete database such as MySQL.

With all the layers that our framework has, one of the main ones is data management, in other words, it is part of our database, which can be of various types such as MySQL, MariaDB, PostgreSQL, among others.

One of the parts that can generate the most doubt is how to connect Django with MySQL.

Although the framework comes with SQLite by default, as soon as a project grows or is deployed in production, MySQL becomes a more robust and scalable option.

In this guide, I show you how to integrate Django with MySQL step by step, just as I do in my real projects. We will see requirements, installation, configuration, and how to solve the most common errors.

Why use MySQL with Django?

Even though Django works perfectly with SQLite, MySQL offers key advantages:

  • Scalability: ideal for production environments with multiple users.
  • Compatibility: many hosting services support MySQL natively.
  • Advanced management: you can use tools like MySQL Workbench or phpMyAdmin.

It is important to mention that Django officially supports several engines:

  • PostgreSQL
  • MariaDB
  • MySQL
  • Oracle
  • SQLite (which is the one that comes by default).

Connectors for each database engine

Django can connect to MySQL using two drivers:

  • mysqlclient (official)
  • PyMySQL (alternative, more flexible)

Driver Selection: mysqlclient vs. PyMySQL

The main thing you have to keep in mind when you want to connect to a database engine is that the connector simply varies; that is, depending on the database server you want to connect to, you simply have to change the connector, and in the official documentation that I leave a little further down, you will be able to see the different types of connectors you can use and with them the different clients.

To connect Django with MySQL we need a "driver". There are two main options:

  • mysqlclient (Official): It is the driver recommended by Django. Its main advantage is performance, but it usually gives installation problems because it tries to compile C files. This requires having development tools installed on the operating system, which can be tedious in environments like Mac or on production servers like PythonAnywhere.
  • PyMySQL: It is an alternative written purely in Python. It does not require compilation, so it is much easier to install in any environment, although technically Django does not recognize it natively without a small "trick".

mysqlclient, the official driver

We can install the official driver using:

$ pip install mysqlclient  

In Django since version 3, we can use a native Driver for MySQL and for MariaDB. You are free to try the official solution, but in case you get an error like the following:

*** no se puede abrir el archivo incluir 'mysql.h' ***
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 1022, in exec_module
  File "<frozen importlib._bootstrap_external>", line 1160, in get_code
  File "<frozen importlib._bootstrap_external>", line 1090, in source_to_code
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "/Users/andrescruz/Desktop/proyects/django/mystore/mystore/settings.py", line 95

Installation with PyMySQL (Recommended option for ease)

Since mysqlclient usually gives compilation errors if C libraries (the language it uses internally) are missing, we can use PyMySQL instead, which we cover in the next section.

Solving the previous errors

However, you can try the following steps to install the official Driver:

$ brew install mysql-client pkg-config

Configure the environment variables (this is what the error asks for at the end). You must tell your Mac where the MySQL files you just downloaded are. Run this before trying the pip install:

export FLAGS=$(pkg-config --cflags --libs mysqlclient)
export LDFLAGS="-L/opt/homebrew/opt/mysql-client/lib"
export CPPFLAGS="-I/opt/homebrew/opt/mysql-client/include"

Try to install again:

$ pip install mysqlclient

Testing the NON-official version of the MySQL connector

We can try another solution, which would be to install a package that will serve as a driver or connector to our MySQL, which is the following:

$ pip install PyMySQL

For Django to accept PyMySQL as if it were the official driver, we must go to the __init__.py file in our project folder (where the settings.py file is) and add the following code:

firstProject\firstProject\__init__py

import pymysql
pymysql.version_info = (2, 2, 7, "final", 0) # Definimos una versión compatible, el 2 2 7 corresponde a la version actual de mysqlclient
pymysql.install_as_MySQLdb()

Configuration of the settings.py file

Once any of the drivers are installed, we must modify the DATABASES dictionary in our project. We will change the engine from SQLite to MySQL and define the connection parameters:

firstProject\firstProject\settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'djangofirstproyect',
        'USER': 'root',
        'PASSWORD': ''
    }
}

And with this, we are ready to perform more interesting operations using our MTV in Django, which we will do starting from the next post.

  • DATABASE_NAME We indicate the name of the database. If you are using SQLite, specify the full path including the file system to the file/database.
  • DATABASE_USER We indicate which database user we are going to use to connect to the previous database.
  • DATABASE_PASSWORD We indicate the password for the previous user.
  • DATABASE_HOST This is one of the most important elements, and it is the host; if we are in a development environment it will surely be localhost or local server, but if you are in a production environment it is very likely to change to another one or an IP.

Depending on the database you are going to use, you will surely have to add more or fewer parameters; for example, in the case of SQLite, which is the one that comes by default, it is not necessary to indicate either user/password or host, since it is simply a file.

Once settings.py is configured, run the migrations in Django to verify the connection:

$ python manage.py migrate

❗ Common errors when connecting Django with MySQL (and how I solved them)

During my first tests, I came across some typical errors:

Error    Cause    Solution
cannot open mysql.h    Missing MySQL client dependencies    Install PyMySQL or install libmysqlclient-dev on Linux
Access denied for user 'root'@'localhost'    Incorrect password or user without permissions    Check USER and PASSWORD in settings.py
django.db.utils.OperationalError    MySQL not started    Verify that the service is active (sudo service mysql start)

These small setbacks are common. In my case, with PyMySQL everything worked without complications.

⚖️ PyMySQL vs mysqlclient: which one is better?

Aspect    PyMySQL    mysqlclient
Installation    Very simple, no compilation    Requires system dependencies
Performance    Lightweight and sufficient for most projects    Somewhat faster in large databases
Compatibility    Works well on Windows, macOS, and Linux    Sometimes gives errors on Windows
Recommendation    Ideal for development and medium environments    Recommended in production if your environment allows it

I prefer PyMySQL for its ease and stability, especially when working on Windows or virtualized environments.

Conclusion and next steps

With this, you now have your Django project connected to MySQL and ready to build models, views, and migrations.
In my experience, this configuration remains stable even when deploying to production.
The natural next step is to create your models and start manipulating data from the Django ORM.

❓ Frequently Asked Questions

  • Can I use MariaDB instead of MySQL?
    • Yes, Django is natively compatible since version 3.
  • How do I test if my connection works?
    • Run python manage.py migrate or use python manage.py dbshell.
  • What do I do if PyMySQL doesn't work?
    • Check your Python and Django versions, reinstall with pip install --upgrade PyMySQL.

We are going to learn how to set up a MySQL database using the UNofficial extension or package for Python in our Django project, but remember that you can use several types of servers in your project.

I agree to receive announcements of interest about this Blog.

Andrés Cruz

ES En español