DEV Community

Cover image for Django shorts: #2 Environment variables
Arno Pretorius
Arno Pretorius

Posted on • Originally published at cloudwithdjango.com

Django shorts: #2 Environment variables

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
Enter fullscreen mode Exit fullscreen mode

Step 2:

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

# settings.py

import environ
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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’)
Enter fullscreen mode Exit fullscreen mode

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.


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

Top comments (0)