📝 Django

Environment Variables in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
79
🌿
Level
Medium

Охватываемые темы: Why use environment variables, python-dotenv, django-environ (alternative), .gitignore.

Why use environment variables

  • Secrets (SECRET_KEY, passwords) never end up in git
  • Different settings for dev/prod without changing code

python-dotenv

pip install python-dotenv
# .env (in the project root, do NOT commit)
SECRET_KEY=django-insecure-abc123
DEBUG=True
DATABASE_URL=sqlite:///db.sqlite3
ALLOWED_HOSTS=localhost,127.0.0.1
# settings.py
from pathlib import Path
from dotenv import load_dotenv
import os

load_dotenv()

SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = os.environ.get('DEBUG', 'False') == 'True'
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')

django-environ (alternative)

pip install django-environ
import environ
env = environ.Env()
environ.Env.read_env('.env')

DEBUG = env.bool('DEBUG', default=False)
SECRET_KEY = env.str('SECRET_KEY')
DATABASES = {'default': env.db('DATABASE_URL')}

.gitignore

.env
*.env
.env.local

.env.example (template for the team)

# .env.example — commit this to the repository
SECRET_KEY=your-secret-key-here
DEBUG=True
DATABASE_URL=sqlite:///db.sqlite3
ALLOWED_HOSTS=localhost

Production check

# Railway, Heroku, Docker: variables are set on the platform
# No .env file needed on the server
export SECRET_KEY="production-secret"
export DEBUG="False"

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 138
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 85
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 77

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!