Environment-based settings help you keep different configurations for development, testing, and production. This keeps your app safe and easy to manage.
0
0
Environment-based settings in Django
Introduction
When you want to use different database passwords for development and production.
When you want to turn on debug mode only during development.
When you need to change API keys without changing your code.
When deploying your app to different servers with different settings.
When you want to keep sensitive information out of your code.
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
This sets
DEBUG to True only if the environment variable DJANGO_DEBUG is set to 'True'.Django
DEBUG = os.getenv('DJANGO_DEBUG', 'False') == 'True'
Reads the secret key from environment or uses a default (not recommended for production).
Django
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', 'default-secret-key')
Reads allowed hosts as a comma-separated string and converts it to a list.
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']}")
OutputSuccess
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.