How to set up environment variables in Django

Alice Ridgway
2 min readSep 17, 2020

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

In your terminal, inside the project directory, type:

$ pip install django-environ

2. Import environ in

import environ

3. Initialise environ

Below your import in

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

4. Create your .env file

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

5. Declare your environment variables in .env

Make sure you don’t use quotations around strings.


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

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.

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.