How to separate local and production settings in django?
I have .env.local and .env.prod files, and I've split settings.py into base, local, and production.
Running a Django app with production settings works without any problems (thanks to docker), but I'm not entirely sure how to easily run it with local settings.
I'm currently doing this with a sh script.
export $(cat .env.local | grep -v '^#' | xargs)
python manage.py runserver
but i dont think that its a best way to launch django with specific .env
i think it would be great to launch it with path to env file as a parametet. Like this
python manage.py runserver --env=./env.local
Anyway, what is the best way to launch django with specific environment (without docker)
Switch environment via settings module
Since you already have
base.py,local.py, andproduction.py, you can run:# local python manage.py runserver --settings=config.settings.local # production python manage.py runserver --settings=config.settings.productionIf you prefer an environment variable:
DJANGO_SETTINGS_MODULE=config.settings.local python manage.py runserverYou can wrap this in a small script / Makefile if you want a shorter command.
Load the correct .env inside settings
Instead of exporting everything before
runserver, read the right.envinside your settings.
For example withdjango-environ:# config/settings/base.py import environ from pathlib import Path BASE_DIR = Path(_file_).resolve().parent.parent.parent env = environ.Env() # Use ENV_PATH if set, otherwise default to .env env.read_env(env.str("ENV_PATH", BASE_DIR / ".env")) SECRET_KEY = env("SECRET_KEY") DEBUG = env.bool("DEBUG", False)Then run:
# local ENV_PATH=.env.local python manage.py runserver --settings=config.settings.local # production-like ENV_PATH=.env.prod python manage.py runserver --settings=config.settings.production