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

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


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

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



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.

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