Django: How to use .env file for storing sensitive setting values

Jatin Prajapati
2 min readJan 16, 2020

--

OK, again while learning I came across a through that how I can use the .env file to store my local/stage/production related setting values which are either local to my system or sensitive enough, like database password/email configuration/etc.., not to share or commit in to the source control.

I wrote a small and simple block of code to read the .env file and set the settings value when the application first loads.

In the above code you can see that I’m loading the .env file from the directory where we have settings.py file resides. In this file I read the .env file lines and then check for the provided key. If the key finds, I return the value otherwise the default will return which is None by default.

As of now, the code only supports to read string/int values. The code does not support the JSON/LIST type of settings from .env file. Also, provide the list type of settings in a single line just like shown below in a sample .env.

EMAIL_HOST = smtp.jatin.prajapati
EMAIL_HOST_USER = jatinpr
EMAIL_HOST_PASSWORD = mysamplepassword
EMAIL_PORT = 578

How to use in settings.py file

First import the file using following command. Make sure you use appropriate app name when you copy the above code and put into your own application.

from django_tabler.envloader import env

Now you can use the ‘env’ function like following in your settings.py file:

EMAIL_HOST = env('EMAIL_HOST')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')
EMAIL_HOST_USER = env('EMAIL_HOST_USER')
EMAIL_PORT = env('EMAIL_PORT')
STATICFILES_DIRS = env('STATICFILES_DIRS')

So, using this small code block we can save the local settings or sensitive information out of the source control and avoid accidental sharing of such information.

Happy Python and Django!!!!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response