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
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.
DEBUG to True only if the environment variable DJANGO_DEBUG is set to 'True'.DEBUG = os.getenv('DJANGO_DEBUG', 'False') == 'True'
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', 'default-secret-key')
ALLOWED_HOSTS = os.getenv('DJANGO_ALLOWED_HOSTS', 'localhost').split(',')
This example shows how to read environment variables to set Django settings. It prints the debug mode and database connection info.
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']}")
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.
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
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]
- Thinking environment settings speed up the app
- Confusing environment settings with file count
- Believing environment settings remove database use
SECRET_KEY in Django settings?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]
- Adding parentheses after os.environ['VAR']
- Using non-existent os.get() function
- Calling getenv() without os prefix
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?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]
- Assuming default 'False' string converts to boolean True
- Expecting None when variable is missing
- Thinking code raises error if env var missing
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?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]
- Assuming os.getenv returns boolean type
- Thinking import order affects env var reading
- Believing dotenv is required for os.getenv
settings.py?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]
- Hardcoding production settings in code
- Not providing default for os.environ access
- Ignoring environment variables for config
Ready to prove it?
Pass the test and this pattern moves unknown
