Connect and Configure MySQL in Django Project

Django is a powerful and popular web framework for Python, widely used for building web applications. It comes with built-in support for various databases, including PostgreSQL, SQLite, and MySQL. In this blog post, we will focus on how to connect MySQL in Django, enabling you to leverage the features of this robust relational database management system with example project. Let’s get started with the step-by-step process:

Prerequisites:

Before we begin, make sure you have the following prerequisites in place:

  1. Python 3 installed on your system.
  2. A working Django project.
  3. MySQL installed and running on your local machine or a remote server.
  4. Virtual Environment, this is optional but recommended. You check our blog here.

Note: For this tutorial, we are using our basic skeleton project for Django. You can also download the project from here.

Step 1: Install Django

Before we begin, ensure you have Python installed on your system. You can download the latest version of Python from the official website. Once you have Python installed, open your command prompt or terminal and use the following command to install Django:

pip install django

Step 2: Install MySQL Database

Next, you need to install the MySQL database server and client on your system. For different operating systems, the process may vary. Refer to the MySQL official documentation for the specific installation instructions based on your OS. Also, make sure to create a new MySQL user and database for your Django project.

Step 3: Configure Django MySql Settings

After installing Django and setting up MySQL, you need to configure your Django project to use the MySQL database. Open your Django project’s settings.py file, usually located inside the project folder. Look for the DATABASES setting and update it with the MySQL configuration:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'your_mysql_database_name',
        'USER': 'your_mysql_user',
        'PASSWORD': 'your_mysql_password',
        'HOST': 'localhost',  # or the hostname where your MySQL server is running
        'PORT': '3306',      # or the port on which your MySQL server is listening
    }
}

Make sure to replace 'your_mysql_database_name', 'your_mysql_user', and 'your_mysql_password' with the appropriate values you set up during the MySQL installation.

Step 4: Install MySQL Client Library

To connect Django to MySQL, you need to install the MySQL client library for Python. This library allows Django to communicate with the MySQL database server. Use the following command to install the MySQL client:

pip install mysqlclient

Step 4.1: If Unable to install mysqlclient with pip (Error Solution)

Defaulting to user installation because normal site-packages is not writeable
Collecting mysqlclient
  Using cached mysqlclient-2.2.0.tar.gz (89 kB)
  Getting requirements to build wheel ... error
  error: subprocess-exited-with-error
  
  × Getting requirements to build wheel did not run successfully.
  │ exit code: 1
  ╰─> [25 lines of output]
      Trying pkg-config --exists mysqlclient
      Command 'pkg-config --exists mysqlclient' returned non-zero exit status 1.
          pkg_name = find_package_name()
        File "setup.py", line 27, in find_package_name
          raise Exception(
      Exception: Can not find valid pkg-config name.
      Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

If you are getting above error wihle install mysqlclient, then run bellow commands and try again – pip install mysqlclient:

sudo apt-get install python3-dev default-libmysqlclient-dev build-essential

Step 5: Create Database Tables

Now that your Django project is configured to use MySQL, it’s time to create the necessary tables in the database. Open your terminal or command prompt, navigate to your Django project directory (the one containing manage.py), and run the following command:

python manage.py migrate

This command will create the required tables in the MySQL database based on your Django project’s models.

Step 6: Test the Connection

At this point, your Django project should be successfully connected to the MySQL database. To ensure everything is working correctly, run the Django development server with the following command:

python manage.py runserver

Visit http://localhost:8000 (or the appropriate URL if you’ve specified a different port) in your web browser. If you see the Django welcome page, congratulations! Your Django project is now connected to MySQL.

Conclusion

In this blog post, we walked through the steps to connect MySQL in Django. By following these steps, you can take advantage of MySQL’s capabilities as a reliable and scalable database for your Django web applications. Remember to install Django, set up MySQL, configure Django settings, install the MySQL client library, create the database tables, and test the connection.

Find this Project on Github.

Blogs you might like to Read!