Set up environment variables in Django

Last updated 3 years, 2 months ago | 1427 views 75     5

Tags:- Django

Django | Set up environment variables 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 is your import in settings.py:

import environ

# Initialise environment variables

env = 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=postgresdatabase

DATABASE_USER=alice

DATABASE_PASS=supersecretpassword

6. 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’)