Django shorts: #2 Environment variables

Arno Pretorius
2 min readOct 9, 2022

How to setup environment variables in Django.

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 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 file:

# settings.pyimport environ

Step 3:

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

# settings.pyimport 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 file:

Step 5:

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

# .env fileTHE_SECRET_KEY=g^31535r/g/wd65ognj66=xh7t05$w7q8!0_3zsl#g

Step 6:

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

# settings.pySECRET_KEY = env(‘THE_SECRET_KEY’)

Note:* You are effectively referencing your environment variable, just within your 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.

A final note…
For those that are interested in learning how to secure their Django web application as well as how to add 2FA, feel free to check out my latest course:

Python Django: Ultimate Web Security Checklist- 2022

Originally published at on October 9, 2022.



Arno Pretorius

Hi, I’m Arno… I love cloud computing and django web development and I want to share my knowledge and experiences with you.