Setting environment variables for Django in Linux
22 September, 2020
tl;dr (assuming you use Bash as your shell)
# open the login script file bashrc sudo nano ~/.bashrc # add your environment variable with this syntax export MY_NEW_ENV_VAR='billybiscuits'
The easiest way to set persistent environment variables (i.e., those that do not disappear when you start a new terminal session) that Django can read is to add them to the
.bashrc file is essentially a Bash script that is executed when a new terminal is opened. It is where we can set environment variables. If you use a different shell, like FSH or ZSH, you will need to use the equivalent file.
.bashrc should live in your $HOME directory as a hidden file, so if you simply list the contents of your $HOME path (or
~), you won't see it. To see hidden files, run
ls with the
username@computer: ~$ ls -la
Open the script with your favourite, second favourite or least favourite editor:
sudo nano ~/.bashrc
Scroll down to the bottom, and add your environment variable with the following syntax:
Note that this is quite a useful environment variable to set, so I always do this on my local machine. It allows us to specify separate
settings.py configuration files for development and production environments (for example, allowing us to safely set
DEBUG=True locally, which would be a terrible idea in production).
Accessing from Django (or more generally, Python)
import os SECRET_KEY = os.getenv('MY_SECRET_KEY')
This method describes how you can set environment variables on your local machine, to be read in a development environment. This will not work on your Digital Ocean droplet running a Gunicorn webserver, because you aren't opening a new terminal window every time you navigate to your site!
Further reading for the nerds
- What is the .bashrc file? from the Unix StackExchange.