1 min read

Django shorts: #1 Environment variables

Django shorts: #1 Environment variables
Photo by Mohammad Rahmani / Unsplash

Why do we need to set up environment variables in Django?

As we continue to build our Django web application, we will eventually come to a realization that there is a lot of sensitive information that is stored in our settings.py file. Typical examples of this sensitive information may include API keys and passwords. Upon realizing the need to keep prying eyes from this type of information, you will think, how can I keep everything separate and safe.

Step 1:

First of you head over to your terminal and install django-environ via the following command:

pip install django-environ

Django-environ is a python package which we can use to create environments variables within our Django web app.

Step 2:

Next, be sure to import environ in your settings.py file:

# settings.py

import environ

Step 3:

We now need to define and initialize environ at the top of our settings.py file:

# settings.py

import environ

# Define and Initialise environment variables 

env = environ.Env()


Step 4:

Be sure to create a .env file within the same directory as your settings.py file:

Step 5:

Declare your environment variable(s) in your .env file:

# .env file


Step 6:

Be sure to add your newly declared environment variable in settings.py, and replace the value according as follows:

# settings.py


Note:* You are effectively referencing your environment variable, just within your settings.py file now.


Make sure that upon pushing your code to your git repository that you create a .gitignore file and add your .env file to it. This ensures that no-one will be able to see sensitive information within your .env file.