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
In your terminal, inside the project directory, type:
$ pip install django-environ
2. Import environ in settings.py
import environ
3. Initialise environ
Below your import in settings.py:
import environ# Initialise environment variablesenv = environ.Env()environ.Env.read_env()
4. Create your .env file
In the same directory as settings.py, create a file called ‘.env’
5. Declare your environment variables in .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
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 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.