Registry / web-framework / django-configurations

django-configurations

JSON →
library2.5.1pypypi✓ verified 23d ago

django-configurations is a helper library for organizing Django project settings by leveraging Python's class inheritance. It extends Django's module-based settings system with object-oriented patterns like mixins and facades, making complex configuration scenarios more manageable, especially for Twelve-Factor app deployments. The current version is 2.5.1, and it maintains an active release cadence with regular updates for new Python and Django versions.

pip install django-configurations
INSTALL
IMPORT
SIG · DJANGO-CONFIGURATI
D
django-configurations
web-frameworkpythonv2.5.1
Install
4.0s avg
Import
325ms
Disk
67MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.5.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.350s · 68MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 4.0s · import 0.300s · 69MB
67MB installed
● package 67MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Configuration
from configurations import Configuration
This is the primary base class for defining your Django settings.
values
from configurations import values
Used for defining settings that can read from environment variables or provide type validation.
execute_from_command_line
from configurations.management import execute_from_command_line
from django.core.management import execute_from_command_line
django-configurations requires its own management command runner to correctly load settings.
get_wsgi_application
from configurations.wsgi import get_wsgi_application
from django.core.wsgi import get_wsgi_application
For WSGI deployments, you must use django-configurations's WSGI application loader.

To use django-configurations, subclass `configurations.Configuration` (or `configurations.Settings` for older versions, though `Configuration` is preferred). Define your settings as class attributes, optionally using `configurations.values` for type-casting environment variables. Modify your `manage.py` and `wsgi.py` files to use `configurations.management.execute_from_command_line` and `configurations.wsgi.get_wsgi_application` respectively. The specific configuration class to load is determined by the `DJANGO_CONFIGURATION` environment variable.

# mysite/settings.py import os from configurations import Configuration, values class Common(Configuration): # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = values.SecretValue() DEBUG = values.BooleanValue(False) ALLOWED_HOSTS = values.ListValue(['localhost', '127.0.0.1']) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Your apps here ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mysite.wsgi.application' DATABASES = values.DatabaseURLValue('sqlite:///db.sqlite3') AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = '/static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' class Dev(Common): DEBUG = values.BooleanValue(True, environ_name='DJANGO_DEBUG') # Use DJANGO_DEBUG env var, default True # mysite/manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') os.environ.setdefault('DJANGO_CONFIGURATION', os.environ.get('DJANGO_CONFIGURATION', 'Dev')) try: from configurations.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) # mysite/wsgi.py import os from configurations.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') os.environ.setdefault('DJANGO_CONFIGURATION', os.environ.get('DJANGO_CONFIGURATION', 'Common')) application = get_wsgi_application() # For local development, run: # export DJANGO_CONFIGURATION=Dev # python manage.py runserver
Debug
Known issues
breakingThe `configurations.Settings` class was removed in version 2.0 in favor of `configurations.Configuration`. Projects upgrading from very old versions must update their base settings class.
fix
Change `from configurations import Settings` to `from configurations import Configuration` and adjust your settings class inheritance.
affects: >=2.0
breakingVersion 2.3 dropped support for Python 2.7 and 3.5, and Django versions older than 2.2. Subsequent major versions have continued to raise the minimum Python and Django requirements.
fix
Ensure your project runs on Python >=3.8 (currently >=3.9 recommended) and Django >=3.2 (currently >=3.2 required). For example, version 2.4 dropped Python 3.6 and Django < 3.2 support, and version 2.5 dropped Python 3.7 and Django 4.0 support.
affects: >=2.3
gotchaYou must use django-configurations's custom `execute_from_command_line` and `get_wsgi_application` functions in your `manage.py`, `wsgi.py`, and `asgi.py` files. Not doing so will prevent your configurations from being loaded correctly.
fix
Update your `manage.py` to import `execute_from_command_line` from `configurations.management` and your `wsgi.py` (and `asgi.py` if applicable) to import `get_wsgi_application` from `configurations.wsgi` or `configurations.asgi`.
affects: All versions
gotchaDjango-configurations relies on the `DJANGO_SETTINGS_MODULE` and `DJANGO_CONFIGURATION` environment variables. The `DJANGO_CONFIGURATION` variable specifies which settings class to load from your `DJANGO_SETTINGS_MODULE`.
fix
Always set `DJANGO_SETTINGS_MODULE` to the path of your settings file (e.g., `mysite.settings`) and `DJANGO_CONFIGURATION` to the name of your desired settings class (e.g., `Dev`, `Prod`). This can be done via shell exports, `.env` files, or directly in your entrypoint scripts (e.g., `manage.py`).
affects: All versions
deprecatedThe utility function `configurations.utils.import_by_path` was deprecated in version 2.3.
fix
Use `django.utils.module_loading.import_string` instead.
affects: >=2.3
Errors
Common errors & fixes
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
This error occurs when Django's settings have not been properly loaded or made available to the application, typically because the `DJANGO_SETTINGS_MODULE` environment variable is not set or is set incorrectly, and `django-configurations` also requires `DJANGO_CONFIGURATION`.
fix
Ensure both `DJANGO_SETTINGS_MODULE` and `DJANGO_CONFIGURATION` environment variables are set before running Django commands. For example, in your `manage.py` and `wsgi.py`/`asgi.py` files, or in your shell/deployment environment.

Example for `manage.py`:
```python
import os
import sys

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings')
    os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev') # Or your chosen configuration class name
    
    from configurations.management import execute_from_command_line

    execute_from_command_line(sys.argv)
```

Example for `wsgi.py`:
```python
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project_name.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Production') # Or your chosen configuration class name

from configurations.wsgi import get_wsgi_application

application = get_wsgi_application()
```
django.core.exceptions.ImproperlyConfigured: django-configurations settings importer wasn't correctly installed.
This error specifically indicates that the `django-configurations` setup function (`configurations.setup()`) was not called, or the entry points (`configurations.management.execute_from_command_line`, `configurations.wsgi.get_wsgi_application`, `configurations.asgi.get_asgi_application`) were not used to initialize Django's settings system.
fix
Modify your `manage.py`, `wsgi.py`, and/or `asgi.py` files to use the respective `django-configurations` entry points. Ensure `os.environ.setdefault('DJANGO_CONFIGURATION', 'YourConfigurationName')` is also set.

Example for `manage.py`:
```python
import os
import sys
from configurations.management import execute_from_command_line

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
os.environ.setdefault('DJANGO_CONFIGURATION', 'Development') # Name of your settings class

if __name__ == '__main__':
    execute_from_command_line(sys.argv)
```
ModuleNotFoundError: No module named 'your_project_name.settings'
Django or `django-configurations` cannot find the Python module specified by `DJANGO_SETTINGS_MODULE`. This can be due to a typo in the module name, the file not existing, the project's root directory not being on the Python path, or missing `__init__.py` files making a directory not a valid Python package.
fix
Double-check the `DJANGO_SETTINGS_MODULE` environment variable for typos. Ensure the path `your_project_name.settings` correctly reflects the location of your settings file (`settings.py`) relative to a directory on your `PYTHONPATH`. Add `__init__.py` files to make sure all relevant directories (e.g., `your_project_name/`) are recognized as Python packages.
AttributeError: 'Settings' object has no attribute 'SECRET_KEY'
This error indicates that a Django setting, such as `SECRET_KEY`, is being accessed, but it's not defined within the active `django-configurations` settings class or its environment variables. This often happens if an environment variable expected by the `Configuration` subclass isn't loaded, or a required setting is simply missing.
fix
Ensure that all required settings, like `SECRET_KEY`, are defined in your `Configuration` subclass or provided via environment variables that `django-configurations` is configured to read. For sensitive values, use `os.environ.get()` with a default or raise an `ImproperlyConfigured` exception if missing.

Example in `settings.py`:
```python
from configurations import Configuration
import os

class Common(Configuration):
    # ... other settings

    SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'a-very-insecure-default-key-for-development')
    if not SECRET_KEY:
        from django.core.exceptions import ImproperlyConfigured
        raise ImproperlyConfigured('The DJANGO_SECRET_KEY environment variable must be set.')

    # ...
```
ModuleNotFoundError: No module named 'configurations'
The 'django-configurations' package is not installed in the current Python environment.
fix
Run `pip install django-configurations` to install the package.
Upgrade
Version history
2.5.1latest on PyPI · released Mar 27, 2024
Audit
Dependencies
djangorequiredCore dependency for Django projects.
django-cache-urloptionalOptional, for URL-based cache configuration.
dj-database-urloptionalOptional, for URL-based database configuration.
dj-email-urloptionalOptional, for URL-based email configuration.
dj-search-urloptionalOptional, for URL-based search configuration.
Agent activity
7 hits · last 30 days
node
6
Resources
django-configurations — pip install django-configurations · libregistry