Setting environment variables for Django in Linux

Python Django 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'

.bashrc

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.

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 -la flag:

username@computer: ~$ ls -la

Syntax

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:

export DJANGO_DEVELOPMENT='True'

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')

A caveat

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



0 comments

Leave a comment