Django Dotenv
django-dotenv is a Python library designed to simplify the loading of environment variables from .env files specifically within Django projects. It aims to make `manage.py` and WSGI applications aware of .env configurations, addressing a common configuration challenge for Django applications. As of its last release, it offers basic .env file parsing functionality.
Warnings
- breaking Support for Python 2.6 and Python 3.2 was removed in version 1.4.1. Projects still using these Python versions will need to either upgrade their Python environment or pin `django-dotenv` to an earlier version (e.g., `<1.4.1`).
- gotcha A common `AttributeError: module 'dotenv' has no attribute 'read_dotenv'` occurs if `python-dotenv` is installed alongside `django-dotenv`. The `dotenv` module provided by `python-dotenv` can shadow the `django-dotenv`'s module, causing the `read_dotenv` function to be unavailable.
- gotcha By default, environment variables already defined in the shell take precedence over those specified in the `.env` file. This means shell variables will not be overridden by the `.env` file's contents unless explicitly instructed.
- gotcha The `django-dotenv` library has not been actively maintained since its last release (v1.4.2) in December 2017. For new projects or more robust and actively maintained `.env` handling, the `python-dotenv` library is generally recommended as a more universal solution, even for Django applications, due to its ongoing development and broader feature set.
Install
-
pip install django-dotenv
Imports
- read_dotenv
import dotenv; dotenv.read_dotenv()
Quickstart
import os
import dotenv
# Recommended to call early in manage.py or wsgi.py
# For manage.py, place before os.environ.setdefault(...)
# For wsgi.py, place before application = get_wsgi_application()
dotenv.read_dotenv()
# Access environment variables as usual
SECRET_KEY = os.environ.get('SECRET_KEY', 'your-fallback-secret-key')
DEBUG = os.environ.get('DEBUG', 'False').lower() == 'true'
DATABASE_URL = os.environ.get('DATABASE_URL', '')
print(f"SECRET_KEY: {SECRET_KEY}")
print(f"DEBUG: {DEBUG}")
print(f"DATABASE_URL: {DATABASE_URL}")