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 offers a ready-to-use MySQL cloud solution that provides a host of benefits, including:
- Unlimited connections and transfers.
- phpMyAdmin web UI included.
- Effortless updates with just a click.
- Optimal performance and robust security powered by a private and dedicated VM.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's MySQL cloud hosting solution!
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 nameerror during installation, you might need to add thelibmysqlclientpackage. 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