MySQL: Using MySQL with Django

This documentation is part of the Getting started guide. View the full guide here: How to get started with MySQL.

👋 Welcome to the Stackhero documentation!

Stackhero provides a fully managed MySQL cloud service that simplifies deployment and management for production workloads:

  • Unlimited connections and data transfers.
  • Integrated phpMyAdmin web interface for easy database management.
  • Hassle-free updates with one-click upgrades.
  • Consistent performance and strong security on a private, dedicated infrastructure.

With Stackhero, you can have a reliable MySQL database ready in just a few minutes. Spend less time on setup and maintenance, and more time building your applications. Try MySQL cloud hosting on Stackhero today.

If you have not installed the mysqlclient module yet, you can do so with:

pip install mysqlclient

If you run into the Exception: Can not find valid pkg-config name error during installation, you might need to add the libmysqlclient package. On Ubuntu/Debian, this can be done with: apt-get update && apt-get install --no-install-recommends -y libmysqlclient-dev

Initially, you may want to test your connection by storing the password directly in your settings.py file. For long-term security, however, it is best to use environment variables (see below).

Edit your settings.py like this:

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'HOST': '<XXXXXX>.stackhero-network.com',
    'PORT': '<PORT>',
    'OPTIONS': {
      'ssl_mode': 'REQUIRED',
    },
    'NAME': 'root',
    'USER': 'root',
    'PASSWORD': '<ROOT_PASSWORD>'
  }
}

Please note: This example is for testing only and not recommended for production environments!

After confirming your connection works, you can switch to a more secure approach using django-environ to manage environment variables.

First, install the package:

pip install django-environ

Then, update your settings.py:

import environ
env = environ.Env()
environ.Env.read_env()

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'HOST': env('STACKHERO_MYSQL_HOST'),
    'PORT': env('STACKHERO_MYSQL_PORT'),
    'OPTIONS': {
      'ssl_mode': 'REQUIRED',
    },
    'NAME': 'root',
    'USER': 'root',
    'PASSWORD': env('STACKHERO_MYSQL_ROOT_PASSWORD')
  }
}

Create or edit the .env file in the same directory as settings.py and add:

STACKHERO_MYSQL_HOST=<XXXXXX>.stackhero-network.com
STACKHERO_MYSQL_PORT=<PORT>
STACKHERO_MYSQL_ROOT_PASSWORD=<ROOT_PASSWORD>

Finally, to keep your credentials safe, you can add .env to your .gitignore file:

echo ".env" >> .gitignore