0
0
Djangoframework~5 mins

Environment variables for secrets in Django

Choose your learning style9 modes available
Introduction

Environment variables keep secret information safe outside your code. This helps protect passwords and keys from being shared by mistake.

When you need to store a database password securely.
When you want to keep API keys hidden from your code repository.
When deploying your Django app to different servers with different secrets.
When sharing your code but not your private keys or passwords.
Syntax
Django
import os

SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
Use os.getenv('VARIABLE_NAME') to read environment variables in Django settings.
Set environment variables outside your code, for example in your terminal or hosting service.
Examples
Read a boolean environment variable with a default value.
Django
import os

DEBUG = os.getenv('DJANGO_DEBUG', 'False') == 'True'
Get the database password from an environment variable.
Django
import os

DATABASE_PASSWORD = os.getenv('DB_PASSWORD')
Read a list of hosts from a comma-separated environment variable.
Django
import os

ALLOWED_HOSTS = os.getenv('DJANGO_ALLOWED_HOSTS', '').split(',')
Sample Program

This example shows how to read secret key and debug mode from environment variables in Django. Normally, you set these variables outside your code, but here we simulate them for demonstration.

Django
import os

# Simulate environment variables (in real use, set these outside Python)
os.environ['DJANGO_SECRET_KEY'] = 'supersecretkey123'
os.environ['DJANGO_DEBUG'] = 'True'

SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')
DEBUG = os.getenv('DJANGO_DEBUG', 'False') == 'True'

print(f"Secret Key: {SECRET_KEY}")
print(f"Debug Mode: {DEBUG}")
OutputSuccess
Important Notes

Never commit your secret keys or passwords directly in your code.

Use a .env file with tools like python-dotenv during development to manage environment variables easily.

Remember to restart your server after changing environment variables.

Summary

Environment variables keep secrets safe outside your code.

Use os.getenv() to read them in Django settings.

Set secrets differently for each environment (development, production).