django
Markdown

env

Installing and Setting Up django-environ

  1. First, install django-environ using pip:
uv run install django-environ
  1. Create a .env file in your project root directory (same level as manage.py):

  2. Add your environment variables to the .env file. Here's a template:

ENVIRONMENT=development
SECRET_KEY=your-secret-key-here
DATABASE_URL=sqlite:///db.sqlite3
# Add other environment variables as needed
  1. Update your settings.py. Make sure the BASE_DIR is in the before the ENV(). Replace your current environment setup with:
from pathlib import Path
import os
import environ

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Initialize environ
env = environ.Env()

# Read .env file
env.read_env(os.path.join(BASE_DIR, ".env"))

# Use environment variables
SECRET_KEY = env("SECRET_KEY")
DEBUG = env.bool("DEBUG", default=False)
ENVIRONMENT = env("ENVIRONMENT", default="production")
  1. Create your context_processors.py file in your project directory (where settings.py is):
from django.conf import settings

def environ_variables(request):
    """
    Add environment variables to the template context.
    """
    return {
        'ENVIRONMENT': settings.ENVIRONMENT,
        # Add other environment variables you want available in templates
    }
  1. Add the context processor to your TEMPLATES setting in settings.py (you've already done this):
TEMPLATES = [
    {
        "OPTIONS": {
            "context_processors": [
                # ... other context processors ...
                "dpone.context_processors.environ_variables",
            ],
        },
    }
]
  1. Add .env to your .gitignore file to keep sensitive information out of version control:
echo ".env" >> .gitignore
  1. Create a .env.example file to show other developers what environment variables are needed:
ENVIRONMENT=development
DEBUG=True
SECRET_KEY=your-secret-key-goes-here
DATABASE_URL=sqlite:///db.sqlite3

Additional Tips:

  • Always use env.bool() for boolean values
  • Use env.int() for integer values
  • Use env.str() for string values (default)
  • Use env.list() for list values
  • Use env.db() for database URLs

Example usage in settings.py:

# Different types of environment variables
DEBUG = env.bool("DEBUG", default=False)
PORT = env.int("PORT", default=8000)
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS", default=["localhost", "127.0.0.1"])
DATABASE_URL = env.db("DATABASE_URL", default="sqlite:///db.sqlite3")

Remember to never commit your actual .env file to version control, only the .env.example template.