Skip to main content

Environment Variables

Minimal settings.py

When you build product using Django, there are config code you need to add to Django settings.

Solution 1

One approach is to split the settings file

settings/base.py
settings/local.py
settings/production.py
settings/test.py

Solution 2

Another approach is ONE settings.py

The settings.py has code patter like this:

# base settings

if 'SOME_ENV' in env:
# override settings based on env variable

SaaS Hammer use this approach for clean and minimal settings file.

We can use Environment Variables to customize the behavior.

Environment

Development

Please create .env.development

Production

Please create .env.production, this file would be used by Docker Compose if you deploy the project to some Linux VPS.

If you deploy the project to Heroku, you can add the Environment Variables using heroku config:set command.

Testing

For local test or CI job, please add system Environment Variables to config.

::: warning The env file should NOT be added to Git repo. :::

Reference

Sample env file for Development

# .env.development

# base
DJANGO_DEBUG=1
ENVIRONMENT=development

# sentry
SENTRY_DSN=change-me

# db
DATABASE_URL=postgres://postgres:postgres@localhost:5432/hammer

# celery
CELERY_BROKER_URL=redis://127.0.0.1:6379/
CELERY_BACKEND=redis://127.0.0.1:6379/

CELERY_FLOWER_USER=flower
CELERY_FLOWER_PASSWORD=change-me

# websocket
CHANNELS_REDIS=redis://127.0.0.1:6379/

# email
USE_MAILHOG=0

Sample env file for Production

# .env.production

# base
DJANGO_DEBUG=0
DJANGO_SECRET_KEY=change-me
ENVIRONMENT=production
DJANGO_ALLOWED_HOSTS=change-me

# sentry
SENTRY_DSN=change-me
# sentry release
SENTRY_AUTH_TOKEN=change-me
SENTRY_ORG=change-me
SENTRY_PROJECT=change-me

# db
# the DATABASE_URL should also match the POSTGRES_XXX values
DATABASE_URL=postgres://user:password@postgres:5432/hammer

POSTGRES_DB=hammer
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_USER=user
POSTGRES_PASSWORD=password

# celery
CELERY_BROKER_URL=redis://redis:6379/
CELERY_BACKEND=redis://redis:6379/

CELERY_FLOWER_USER=flower
CELERY_FLOWER_PASSWORD=change-me

# websocket
CHANNELS_REDIS=redis://redis:6379/

# email
USE_MAILHOG=0

MAILGUN_DOMAIN=change-me
MAILGUN_SENDER_DOMAIN=change-me
MAILGUN_API_KEY=change-me

DJANGO_DEFAULT_FROM_EMAIL=change-me
DJANGO_EMAIL_SUBJECT_PREFIX=change-me

# reCAPTCHA
RECAPTCHA_PUBLIC_KEY=change-me
RECAPTCHA_PRIVATE_KEY=change-me