Privacy Policy
Snippets index

  django-constance setup

django-constance installation and configuration

Install django-constance for the database backend:

#pip install django-constance[database]
pip install django-constance

Configure django-constance:

INSTALLED_APPS = (
    ...
    'constance',
    'constance.backends.database',
    ...
)

CONSTANCE_BACKEND = 'constance.backends.database.DatabaseBackend'
# CONSTANCE_DATABASE_PREFIX = 'constance:myproject:'
CONSTANCE_SUPERUSER_ONLY = False

CONSTANCE_CONFIG = {
    'THE_ANSWER': (42, 'Answer to the Ultimate Question of Life, '
                       'The Universe, and Everything'),
}

Configure django-constance with fieldsets:

from collections import OrderedDict
# Delayed ugettext
ugettext = lambda s: s

CONSTANCE_CONFIG = OrderedDict([
    # General
    ('THE_ANSWER', (42, 'Answer to the Ultimate Question of Life')),
    ('DEBUG_SHOW_TOOLBAR', (False, 'Show Debug Toolbar', )),
])

CONSTANCE_CONFIG_FIELDSETS = OrderedDict([
    (ugettext('General'), (
        'THE_ANSWER',
        'DEBUG_SHOW_TOOLBAR',
    )),
])

Eventually add the context processor:

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                ...
                'constance.context_processors.config',
            ],
            ...
        },
    },
]

And finally:

python manage.py migrate

Caching

The database backend has the ability to automatically cache the config values and clear them when saving.

Assuming you have a CACHES setting set, you only need to set the CONSTANCE_DATABASE_CACHE_BACKEND setting to the name of the configured cache backend to enable this feature, e.g. “default”:

pip install django-redis
PROJECT_NAME = "whatever"
PROJECT_INSTANCE = "whatever"
try:
    from main.settings.project_instance import *
except Exception as e:
    pass

# redis url schemes:
#   redis://[:password]@localhost:6379/0
#   unix://[:password]@/path/to/socket.sock?db=0
#REDIS_URL = 'unix:///tmp/redis.sock?db=0'a

REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379/0')
CACHE_URL = os.environ.get('CACHE_URL', 'redis://localhost:6379/0')

CACHES = {
    "default": {
        #"BACKEND": "django.core.cache.backends.redis.RedisCache",
        "BACKEND": "django_redis.cache.RedisCache",
        'LOCATION': CACHE_URL,
        "KEY_PREFIX": PROJECT_INSTANCE,
        #'TIMEOUT': 60 * 60 * 24,
    }
}

#SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'A

then:

# automatically cache the config values and clear them when saving
CONSTANCE_DATABASE_CACHE_BACKEND = 'default'

Usage

In Python code:

from constance import config

# ...

if config.THE_ANSWER == 42:
    answer_the_question()

In templates:

from django.shortcuts import render
from constance import config

def myview(request):
    return render(request, 'my_template.html', {
        'config': config,  # unless constance context_processor is in use
    })
<h1>Welcome on {{ config.SITE_NAME }}</h1>