django-environ
package
django-environ
is a library that helps manage environment variables in Django projects. It allows you to configure your Django settings via environment variables, which is useful for separating configuration from code, enhancing security, and making your application more flexible for different environments (development
, testing
, production
).
Why Use django-environ?
- Security: Keep sensitive data like secret keys and database passwords out of your source code.
- Flexibility: Easily change settings for different environments without modifying the code.
- Convenience: Manage configuration in a central place, usually through a
.env
file.
Basic Usage
-
Install
django-environ
: -
Create a
.env
File: -
Configure Django Settings:
# settings.py import environ # Initialize environment variables env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file environ.Env.read_env() # Take environment variables from .env file DEBUG = env('DEBUG') SECRET_KEY = env('SECRET_KEY') DATABASES = { 'default': env.db(), }
Advanced Usage
-
Handling Different Data Types:
-
Default Values and Casting:
-
Complex Nested Settings:
Example Project Structure
myproject/
├── .env
├── manage.py
├── myproject/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
Sample .env
File
DEBUG=True
SECRET_KEY=your-secret-key
DATABASE_URL=psql://user:password@localhost:5432/dbname
ALLOWED_HOSTS=localhost, .yourdomain.com
CACHE_URL=redis://127.0.0.1:6379/1
EMAIL_PORT=587
EMAIL_USE_TLS=True
LOGGING_LEVEL=DEBUG
By using django-environ
, you can maintain clean and secure configurations, making your project easier to manage and deploy across different environments.
Reference
- How to set up environment variables in Django
- github
- Django Environment Variables
- django-environ with Lists Environment Varibles in .env Files