Installing and Setting Up django-environ
- First, install django-environ using pip:
uv run install django-environ
Create a
.envfile in your project root directory (same level as manage.py):Add your environment variables to the
.envfile. Here's a template:
ENVIRONMENT=development
SECRET_KEY=your-secret-key-here
DATABASE_URL=sqlite:///db.sqlite3
# Add other environment variables as needed
- 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")
- Create your
context_processors.pyfile 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
}
- Add the context processor to your
TEMPLATESsetting insettings.py(you've already done this):
TEMPLATES = [
{
"OPTIONS": {
"context_processors": [
# ... other context processors ...
"dpone.context_processors.environ_variables",
],
},
}
]
- Add
.envto your.gitignorefile to keep sensitive information out of version control:
echo ".env" >> .gitignore
- Create a
.env.examplefile 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.