Skip to content

Instantly share code, notes, and snippets.

@chidimo
Last active February 5, 2018 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chidimo/89b04ebef8617805b8b94509d5762f15 to your computer and use it in GitHub Desktop.
Save chidimo/89b04ebef8617805b8b94509d5762f15 to your computer and use it in GitHub Desktop.
Managing environment variables in Django projects

Technology

Django==2.0, virtualenv==15.1.0, virtualenvwrapper-win==1.2.4

Assumptions

  1. You're using a separatevirtual environment to run each django project.
  2. You're on windows. I'm on windows 10 specifically.

Problem statement 1

How do you handle your django settings.py file properly so that development and production settings are kept clean, apart, and well-organized?

Solution

I followed the suggestion here. I created a directory called settings and put the following python files inside it __init__.py base.py prod.py dev.py You can have as many files in there as you like. All fine and good.

Problem statement 2

When you have multiple projects on your PC, how do you handle the setting and unsetting of environment variables such as SECRET_KEY, DJANGO_SETTINGS_MODULE which varies from project to project?

Solution

Go into the folder of each virtual environment and locate the ../venv_name/scripts/activate.bat and ../venv_name/scripts/deactivate.bat files.

Set environment variables

Open up ../venv_name/scripts/activate.bat with any text editor (notepad will do) At the end of the file type in set "ENV_NAME=ENV_VALUE" Make sure to include the assignment after the set statement inside double quotes. For example, to set the DJANGO_SETTINGS_MODULE environment variable, do

set "DJANGO_SETTINGS_MODULE=path/to/dev/settings"

Use same pattern for all project specific environment variables you wish to set, one per line.

Remove environment variables from current command session (optional)

Open up ../venv_name/scripts/deactivate.bat, at the very end type set ENV_NAME= For example, to remove the DJANGO_SETTINGS_MODULE environment variable, type set DJANGO_SETTINGS_MODULE=. This sets the variable value to null.

This is not required though as setting another variable will overwrite it.

This way you don't have to append --settings=path/to/dev/settings to every django command you issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment