{"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":"en","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,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}