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

environ.Env.read_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

THE_SECRET_KEY=g^31535r/g/wd65ognj66=xh7t05$w7q8!0_3zsl#g

Step 6:

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

# settings.py

SECRET_KEY = env(‘THE_SECRET_KEY’)

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

Step 7 - IMPORTANT:

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.