Environment-based settings help you keep different configurations for development, testing, and production. This keeps your app safe and easy to manage.
Environment-based settings in Django
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Django
import os DEBUG = os.getenv('DJANGO_DEBUG', 'False') == 'True' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST', 'localhost'), 'PORT': os.getenv('DB_PORT', '5432'), } }
Use os.getenv() to read environment variables safely.
Set default values in os.getenv() to avoid errors if variables are missing.
Examples
DEBUG to True only if the environment variable DJANGO_DEBUG is set to 'True'.Django
DEBUG = os.getenv('DJANGO_DEBUG', 'False') == 'True'
Django
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', 'default-secret-key')
Django
ALLOWED_HOSTS = os.getenv('DJANGO_ALLOWED_HOSTS', 'localhost').split(',')
Sample Program
This example shows how to read environment variables to set Django settings. It prints the debug mode and database connection info.
Django
import os # Simulate environment variables for this example os.environ['DJANGO_DEBUG'] = 'True' os.environ['DB_NAME'] = 'mydb' os.environ['DB_USER'] = 'user123' os.environ['DB_PASSWORD'] = 'pass123' os.environ['DB_HOST'] = 'db.example.com' os.environ['DB_PORT'] = '5432' DEBUG = os.getenv('DJANGO_DEBUG', 'False') == 'True' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST', 'localhost'), 'PORT': os.getenv('DB_PORT', '5432'), } } print(f"DEBUG: {DEBUG}") print(f"Database Name: {DATABASES['default']['NAME']}") print(f"Database User: {DATABASES['default']['USER']}") print(f"Database Host: {DATABASES['default']['HOST']}")
Important Notes
Never commit real secret keys or passwords to your code repository.
Use a .env file or your server's environment settings to manage variables.
Use packages like python-dotenv to load environment variables from a file during development.
Summary
Environment-based settings keep your app flexible and secure.
Use os.getenv() to read variables safely.
Keep secrets out of your code and change settings easily per environment.
Practice
1. What is the main reason to use environment-based settings in a Django project?
easy
Solution
Step 1: Understand environment-based settings purpose
They help keep sensitive information like passwords and keys out of the codebase.Step 2: Identify the main benefit
This improves security and allows easy changes per environment without code edits.Final Answer:
To keep sensitive data like passwords out of the code -> Option AQuick Check:
Security = Keep secrets out [OK]
Hint: Environment settings protect secrets outside code [OK]
Common Mistakes:
- Thinking environment settings speed up the app
- Confusing environment settings with file count
- Believing environment settings remove database use
2. Which of the following is the correct way to get an environment variable named
SECRET_KEY in Django settings?easy
Solution
Step 1: Recall correct function to read environment variables
Useos.getenv('VAR_NAME')to safely get environment variables.Step 2: Check syntax correctness
SECRET_KEY = os.getenv('SECRET_KEY') uses correct syntax without extra parentheses or wrong function names.Final Answer:
SECRET_KEY = os.getenv('SECRET_KEY') -> Option CQuick Check:
Use os.getenv() for environment variables [OK]
Hint: Use os.getenv('VAR') to read environment variables [OK]
Common Mistakes:
- Adding parentheses after os.environ['VAR']
- Using non-existent os.get() function
- Calling getenv() without os prefix
3. Given this code in
settings.py:
import os
DEBUG = os.getenv('DEBUG', 'False') == 'True'
What will be the value of DEBUG if the environment variable DEBUG is not set?medium
Solution
Step 1: Understand default value in os.getenv()
IfDEBUGis not set,os.getenv('DEBUG', 'False')returns string 'False'.Step 2: Evaluate comparison to string 'True'
'False' == 'True' is False, soDEBUGbecomes False (boolean).Final Answer:
False -> Option DQuick Check:
Unset DEBUG defaults to 'False' string, so boolean False [OK]
Hint: Default string 'False' != 'True' means DEBUG is False [OK]
Common Mistakes:
- Assuming default 'False' string converts to boolean True
- Expecting None when variable is missing
- Thinking code raises error if env var missing
4. You wrote this in
settings.py:
import os
SECRET_KEY = os.getenv('SECRET_KEY')
DEBUG = os.getenv('DEBUG', False)
But DEBUG is always True even when you set DEBUG=False in the environment. What is the problem?medium
Solution
Step 1: Understand os.getenv returns strings
Environment variables are strings, soos.getenv('DEBUG', False)returns string 'False' if set.Step 2: Recognize string 'False' is truthy in Python
Non-empty strings are True in boolean context, so DEBUG is always True.Final Answer:
os.getenv returns strings, so DEBUG is the string 'False', which is truthy -> Option AQuick Check:
Env vars are strings; 'False' string is True in boolean [OK]
Hint: Remember env vars are strings, not booleans [OK]
Common Mistakes:
- Assuming os.getenv returns boolean type
- Thinking import order affects env var reading
- Believing dotenv is required for os.getenv
5. You want to set different database settings for development and production using environment variables. Which approach correctly applies environment-based settings in
settings.py?hard
Solution
Step 1: Use environment variable to detect environment
Checkos.getenv('ENV')to decide if running in production or development.Step 2: Load DB settings conditionally
Load production DB settings ifENVis 'production', else load development settings.Final Answer:
Use os.getenv('ENV') == 'production' to load production DB settings, else development settings -> Option BQuick Check:
Conditional DB config based on ENV variable [OK]
Hint: Use ENV variable to switch settings safely [OK]
Common Mistakes:
- Hardcoding production settings in code
- Not providing default for os.environ access
- Ignoring environment variables for config
