{"id":1455,"library":"django-environ","title":"django-environ Configuration","description":"django-environ is a Python library that allows Django applications to be configured using 12-factor inspired environment variables. It simplifies parsing various types of settings (e.g., databases, caches, emails, booleans, integers) from `os.environ` or `.env` files into Django-compatible formats. The current version is 0.13.0, with a release cadence that generally follows Django versions and addresses bug fixes.","status":"active","version":"0.13.0","language":"python","source_language":"en","source_url":"https://github.com/joke2k/django-environ","tags":["Django","configuration","environment variables","12factor","settings"],"install":[{"cmd":"pip install django-environ","lang":"bash","label":"Install core library"}],"dependencies":[{"reason":"Core functionality is built around Django's settings system.","package":"Django","optional":false}],"imports":[{"symbol":"Env","correct":"from environ import Env"},{"note":"Used for path handling, typically to define BASE_DIR, etc.","symbol":"Path","correct":"from environ import Path"},{"note":"An exception that can be caught when path-related settings are invalid.","symbol":"InvalidPathSetting","correct":"from environ import InvalidPathSetting"}],"quickstart":{"code":"import environ\nimport os\n\n# --- Simulate environment variables for a runnable example ---\n# In a real application, these would come from your actual .env file or OS environment.\n# For local testing, you might create a .env file like:\n# SECRET_KEY=your-super-secret-key-from-env\n# DEBUG=True\n# DATABASE_URL=sqlite:///myproject.sqlite3\n# EMAIL_URL=smtp://user:password@smtp.example.com:587\n# CACHE_URL=redis://localhost:6379/1\n# ------------------------------------------------------------\n\nos.environ.setdefault('SECRET_KEY', 'your-super-secret-key-for-dev-fallback')\nos.environ.setdefault('DEBUG', 'True')\nos.environ.setdefault('DATABASE_URL', 'sqlite:///myproject.sqlite3')\nos.environ.setdefault('EMAIL_URL', 'smtp://user:password@smtp.example.com:587')\nos.environ.setdefault('CACHE_URL', 'redis://localhost:6379/1')\n\n# Initialize the Env object.\n# You can set default types and values here if not found in .env or os.environ.\nenv = environ.Env(\n    # default type for DEBUG is bool, default value is False if not set\n    DEBUG=(bool, False)\n)\n\n# Optional: Explicitly read .env file. By default, Env.read_env() looks for .env\n# in the current directory and its parents. If you don't call this, it implicitly\n# reads it on the first call to env() or similar, but explicit is better for control.\n# Note: This line assumes a .env file exists. For this example, we're relying on os.environ.setdefault.\n# environ.Env.read_env()\n\n# Accessing environment variables with type casting\nSECRET_KEY = env('SECRET_KEY')\nDEBUG = env('DEBUG') # Uses the (bool, False) casting defined above\n\n# Complex settings like database or cache URLs are parsed into Django-compatible dictionaries\nDATABASES = {\n    'default': env.db() # uses DATABASE_URL from environment\n}\nCACHES = {\n    'default': env.cache() # uses CACHE_URL from environment\n}\nEMAIL = env.email() # uses EMAIL_URL from environment\n\nprint(f\"SECRET_KEY: {SECRET_KEY}\")\nprint(f\"DEBUG: {DEBUG} (type: {type(DEBUG)})\")\nprint(f\"DATABASES (default): {DATABASES['default']}\")\nprint(f\"CACHES (default): {CACHES['default']}\")\nprint(f\"EMAIL (default): {EMAIL}\")\n\n# Example of a missing variable with a default\nAPP_VERSION = env('APP_VERSION', default='1.0.0')\nprint(f\"APP_VERSION: {APP_VERSION}\")","lang":"python","description":"This quickstart demonstrates how to initialize `django-environ`, set up default type casting, and access various types of environment variables including complex ones like database and cache URLs. It simulates environment variables for a runnable example without requiring a physical `.env` file to be present."},"warnings":[{"fix":"Replace `env['KEY']` with `env('KEY', default=...)` or appropriate type-casting methods like `env.str('KEY')`, `env.bool('KEY')`.","message":"The `environ.Env` object no longer inherits from `dict` as of version 0.10.0. This means you cannot treat `env` as a dictionary (e.g., `env['KEY']` or `dict(env)`) directly. Access variables using the callable `env('KEY')` or its type-casting methods like `env.bool('KEY')`.","severity":"breaking","affected_versions":">=0.10.0"},{"fix":"Place `environ.Env.read_env()` early in your `settings.py` file, ideally right after `env` initialization and before any `env()` calls that rely on `.env` variables. Verify the `.env` file path is correct.","message":"For explicit `.env` file loading, ensure `environ.Env.read_env()` is called before `env()` attempts to access variables from the `.env` file. While `environ` attempts to implicitly read `.env` on first access, explicit calls with a correct path (e.g., `environ.Env.read_env(os.path.join(BASE_DIR, '.env'))`) provide better control and prevent unexpected behavior.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always use `env.bool()`, `env.int()`, `env.db()`, `env.cache()`, etc., or constructor-defined type casting for non-string values.","message":"All variables accessed directly with `env('KEY')` are returned as strings. To get booleans, integers, URLs, or other types, you must use the specific type-casting methods (e.g., `env.bool('DEBUG')`, `env.int('TIMEOUT')`, `env.db('DATABASE_URL')`, `env.cache('CACHE_URL')`, `env.url('SITE_URL')`) or define the casting in the `Env` constructor `env = environ.Env(DEBUG=(bool, False))`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"For development, use a fallback default like `env('SECRET_KEY', default='insecure-dev-key')`. In production, ensure `SECRET_KEY` is always provided via `os.environ` or a `.env` file that is securely managed, without a default.","message":"The `SECRET_KEY` is a critical setting. While `django-environ` allows you to retrieve it via `env('SECRET_KEY')`, generating and managing it securely is paramount. Avoid hardcoding a default in production, and ensure it's loaded from a truly secure environment variable or a robust secrets manager.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'0.13.0':52 '12':20 '12factor':70 'address':63 'allow':13 'applic':15 'boolean':36 'bug':64 'cach':34 'cadenc':56 'compat':46 'configur':4,18,67 'current':49 'databas':33 'django':2,6,14,45,60,66 'django-compat':44 'django-environ':1,5 'e.g':32 'email':35 'env':41 'environ':3,7,23,68 'factor':21 'file':42 'fix':65 'follow':59 'format':47 'general':58 'inspir':22 'integ':37 'librari':11 'os.environ':39 'pars':27 'python':10 'releas':55 'set':31,71 'simplifi':26 'type':29 'use':19 'variabl':24,69 'various':28 'version':50,61","created_at":"2026-04-09T03:48:40.332714+00:00","updated_at":"2026-04-16T14:30:18.700444+00:00","problems":[{"fix":"Ensure a `.env` file exists in your project's root directory (or the path specified for `read_env()`). Verify that the variable (e.g., `SECRET_KEY`) is present in the `.env` file with a value. Confirm that `environ.Env.read_env()` is called correctly in your `settings.py` before attempting to access variables. If an environment variable is set externally and needs to be overridden by the `.env` file, pass `overwrite=True` to `env.read_env()` (e.g., `env.read_env(overwrite=True)`).","cause":"This error occurs when `django-environ` cannot find the specified environment variable (e.g., `SECRET_KEY`) because it's missing from the `.env` file, the `.env` file isn't being read, or an existing environment variable is not being overridden.","error":"django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable"},{"fix":"Activate your Python virtual environment if you are using one. Install the `django-environ` package using pip: `pip install django-environ`. Also, check for any local Python files named `environ.py` that might be clashing with the library's import.","cause":"The `django-environ` package (which provides the `environ` module) is not installed in your active Python environment, or the Python interpreter being used is not the one associated with the environment where `django-environ` is installed.","error":"ModuleNotFoundError: No module named 'environ'"},{"fix":"Ensure the `.env` file contains an entry for the missing key (e.g., `SECRET_KEY=your_value`). Verify that `environ.Env.read_env()` is called successfully before you attempt to access the variable using `env('SECRET_KEY')`. For non-critical settings, you can provide a default value to prevent the `KeyError` (e.g., `DEBUG = env('DEBUG', default=False)`).","cause":"This `KeyError` occurs when `env('VAR_NAME')` is called, but the environment variable `VAR_NAME` is not found in `os.environ` after `django-environ` attempts to load variables, and no default value has been provided in the `env()` call.","error":"KeyError: 'SECRET_KEY'"},{"fix":"URL-encode any unsafe characters within the values of your URL-based environment variables in the `.env` file. For instance, replace a pound sign (`#`) in a password with its URL-encoded equivalent (`%23`).\n\n```\n# Original (problematic)\nDATABASE_URL=\"postgres://user:pass#word@host:port/dbname\"\n\n# Fix (URL-encode '#')\nDATABASE_URL=\"postgres://user:pass%23word@host:port/dbname\"\n```","cause":"Special characters such as '#' in URL-parsed environment variables like `DATABASE_URL` are often not properly URL-encoded, causing `django-environ`'s underlying URL parser (which uses `urllib` following RFC 3986) to misinterpret the string (e.g., treating '#' as the start of a comment).","error":"Issues with special characters in DATABASE_URL (e.g., '#' in password)"}],"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"0.14.0","cli_name":"","cli_version":null,"type":"library","homepage":"https://django-environ.readthedocs.org","github":"https://github.com/joke2k/django-environ","docs":"https://django-environ.readthedocs.org","changelog":"https://django-environ.readthedocs.org/en/latest/changelog.html","pypi":"https://pypi.org/project/django-environ/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["web-framework","database"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":"verified"}}