How to set up environment variables in Django

It is important to keep sensitive bits of code like API keys and passwords away from prying eyes. The best way to do this is to not put them on GitHub! Even you’re doing a personal project with no real users, securing your environment variables will build good habits and prevent pesky emails from GitGuardian. Here’s how to do it in Django.

In your terminal, inside the project directory, type:

$ pip install django-environ
import environ

Below your import in settings.py:

import environ# Initialise environment variablesenv = environ.Env()environ.Env.read_env()

In the same directory as settings.py, create a file called ‘.env’

Make sure you don’t use quotations around strings.

SECRET_KEY=h^z13$qr_s_wd65@gnj7a=xs7t05$w7q8!x_8zsld#DATABASE_NAME=postgresdatabaseDATABASE_USER=aliceDATABASE_PASS=supersecretpassword

If you don’t have a .gitignore file already, create one at the project root.

Make sure the name of your .env file is included.

If you’re unsure what other file types belong in the .gitignore, visit this link for a sample.

DATABASES = {‘default’: {‘ENGINE’: ‘django.db.backends.postgresql_psycopg2’,‘NAME’: env(‘DATABASE_NAME’),‘USER’: env(‘DATABASE_USER’),‘PASSWORD’: env(‘DATABASE_PASS’),}}

And

SECRET_KEY = env(‘SECRET_KEY’)

That’s it! Now you’re ready to make your first commit to GitHub.

Thanks for reading.

Full-stack developer and Django enthusiast. When I can’t find Django tutorials, I write them. https://twitter.com/alcampk