MariaDB: Using MariaDB with Django
This documentation is part of the Getting started guide. View the full guide here: How to get started with MariaDB.
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use MariaDB 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 MariaDB cloud hosting solution!
If you have not already, you can install the mysqlclient module to connect Django to MariaDB:
pip install mysqlclient
If you get the error
Exception: Can not find valid pkg-config namewhile installing, you may need to install thelibmysqlclientpackage first. For Ubuntu/Debian:apt-get update && apt-get install --no-install-recommends -y libmysqlclient-dev
To test your connection, you might start by putting your credentials directly into settings.py. This is fine for testing, but it is not secure for a production environment.
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 only for testing. You should not use hardcoded credentials in production.
Once you confirm the connection works, it is safer to store credentials in environment variables. If you use django-environ, you can install it like this:
pip install django-environ
Then update settings.py:
import environ
env = environ.Env()
environ.Env.read_env()
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': env('STACKHERO_MARIADB_HOST'),
'PORT': env('STACKHERO_MARIADB_PORT'),
'OPTIONS': {
'ssl_mode': 'REQUIRED',
},
'NAME': 'root',
'USER': 'root',
'PASSWORD': env('STACKHERO_MARIADB_ROOT_PASSWORD')
}
}
Then, create or update the .env file (in the same directory as settings.py) with:
STACKHERO_MARIADB_HOST=<XXXXXX>.stackhero-network.com
STACKHERO_MARIADB_PORT=<PORT>
STACKHERO_MARIADB_ROOT_PASSWORD=<ROOT_PASSWORD>
Finally, to keep your credentials safe, add .env to your .gitignore:
echo ".env" >> .gitignore