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 Stackhero documentation
Stackhero provides a ready-to-use MariaDB cloud service designed for production workloads. You get:
- Unlimited connections and data transfers.
- Built-in phpMyAdmin web interface for database management.
- One-click updates for easy maintenance.
- High performance and strong security on private, dedicated infrastructure.
Launch a fully managed MariaDB instance in minutes. Stackhero handles setup, updates, and security so you can focus on your application. Learn more about MariaDB cloud hosting.
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