๐Ÿ“ Django

Environment Variables in Django

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
272
๐ŸŒฟ
Level
Medium

Covered topics: 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

๐Ÿ“

Search in Django

You can start with simple Django ORM filters and move to PostgreSQL features when you...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 279
๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 561
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 315
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Django RequestLab: from HTTP to secure production Open course curriculum