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.

1. Install Django Environ

$ pip install django-environ

2. Import environ in settings.py

import environ

3. Initialise environ

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

4. Create your .env file

5. Declare your environment variables in .env

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

6. IMPORTANT: Add your .env file to .gitignore

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.

7. Replace all references to your environment variables in settings.py

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store