Skip to content

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?

  1. Security: Keep sensitive data like secret keys and database passwords out of your source code.
  2. Flexibility: Easily change settings for different environments without modifying the code.
  3. Convenience: Manage configuration in a central place, usually through a .env file.

Basic Usage

  1. Install django-environ:

    pip install django-environ
    
  2. Create a .env File:

    DEBUG=True
    SECRET_KEY=your-secret-key
    DATABASE_URL=psql://user:password@localhost:5432/dbname
    
  3. 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

  1. Handling Different Data Types:

    ALLOWED_HOSTS=localhost, .yourdomain.com
    CACHE_URL=redis://127.0.0.1:6379/1
    
    # settings.py
    ALLOWED_HOSTS = env.list('ALLOWED_HOSTS', default=['localhost'])
    CACHES = {
        'default': env.cache('CACHE_URL')
    }
    
  2. Default Values and Casting:

    EMAIL_PORT=587
    EMAIL_USE_TLS=True
    
    # settings.py
    EMAIL_PORT = env.int('EMAIL_PORT', default=25)
    EMAIL_USE_TLS = env.bool('EMAIL_USE_TLS', default=False)
    
  3. Complex Nested Settings:

    LOGGING_LEVEL=DEBUG
    
    # settings.py
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
            },
        },
        'root': {
            'handlers': ['console'],
            'level': env('LOGGING_LEVEL', default='WARNING'),
        },
    }
    

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