Django Constance
Django Constance is a Django app that enables dynamic settings management, allowing configuration values to be edited directly from the Django admin interface without requiring code changes or redeployments. It supports pluggable backends, including built-in Redis and database options, and is actively maintained with regular releases. The current version is 4.3.5.
Warnings
- breaking Version 3.0.0 introduced backward-incompatible changes, dropping support for Python <3.7 and Django <3.2. Additionally, if you were using the database backend, the `constance.backends.database` entry must be *removed* from `INSTALLED_APPS`.
- gotcha When using admin extensions (like Grapelli) or integrations (like `unfold.contrib.constance`), the order of `constance` in `INSTALLED_APPS` matters. It should typically be placed *before* these extensions to ensure correct template loading.
- gotcha In multi-instance deployments (e.g., Docker Swarm, Kubernetes), hashes generated by `django-constance` might differ between instances, preventing data from being saved via the admin.
- gotcha Synchronous access to `config` (e.g., `config.MY_SETTING`) within asynchronous Django views is highly discouraged. It can block the event loop, degrade performance, and for the Database backend, Django's safety guards might raise a `SynchronousOnlyOperation` error.
- gotcha When setting `MultiValueField` settings via the `constance` management command, separate field values must be provided as individual arguments, not as a single string. E.g., `manage.py constance set DATETIME_VALUE '2011-09-24' '12:30:25'` instead of `'2011-09-24 12:30:25'`.
Install
-
pip install "django-constance[redis]" -
pip install "django-constance[database]"
Imports
- config
from constance import config
Quickstart
import os
# settings.py
# Add 'constance' to your INSTALLED_APPS.
INSTALLED_APPS = [
# ... other Django apps
'constance',
# 'unfold.contrib.constance', # If using Django Unfold, place before 'constance'
]
# Configure backend (example for Redis)
CONSTANCE_BACKEND = 'constance.backends.redisd.RedisBackend'
CONSTANCE_REDIS_CONNECTION = {
'host': os.environ.get('REDIS_HOST', 'localhost'),
'port': int(os.environ.get('REDIS_PORT', 6379)),
'db': int(os.environ.get('REDIS_DB', 0)),
}
# Define your dynamic settings
CONSTANCE_CONFIG = {
'SITE_NAME': ('My Awesome Site', 'The name of the website.'),
'MAINTENANCE_MODE': (False, 'Enable or disable maintenance mode.'),
'MAX_USERS': (1000, 'Maximum allowed users on the platform.'),
}
# In your Django view or anywhere in Python code:
from constance import config
def my_view(request):
if config.MAINTENANCE_MODE:
return HttpResponse("Site is under maintenance.")
site_name = config.SITE_NAME
max_users = config.MAX_USERS
print(f"Current site name: {site_name}")
print(f"Max users: {max_users}")
# ... your view logic
# Run Django migrations if using the database backend
# python manage.py migrate