How to set up Environment Variables in Django?

Published On: 06/08/2022 | Category: Django


Hi Guys,

This simple article demonstrates of how to set up environment variables in django. I would like to show you using environment variables in django. if you want to see example of django environment variables windows then you are a right place. let’s discuss about django env file example.

So, an environment variable is a variable whose value is set outside the program, typically through a functionality built into the operating system. An environment variable is made up like a key/value pair.

Environment variables avail us keep secrets (for example, Passwords, API tokens, and so on) out of version control, consequently, they are considered an integral part of the popular Twelve-Factor App Design methodology and a Django best practice because they sanction a more preponderant level of security and simpler local/engenderment configurations.

let's see below simple example with output:

Step 1 : Install Django Environ

In this first step, we will use django-environ for managing environment variables inside our project. So let's install the package.

pip install django-environ
Step 2 : Creating Environment Variables

Next step we will create a .env file in the same directory where settings.py resides and add the following key-value pair inside the file.

SECRET_KEY=0x!b#(1*cd73w$&azzc6p+essg7v=g80ls#z&xcx*[email protected]$
DATABASE_NAME=db_name
DATABASE_USER=db_user
DATABASE_PASSWORD=password
DATABASE_HOST=localhost
DATABASE_PORT=5432
Step 3 : Update settings.py

Here, we can access the environmental variables in our settings.py file:

import environ

env = environ.Env()
# reading .env file
environ.Env.read_env()

# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env("SECRET_KEY")

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': env("DATABASE_NAME"),
        'USER': env("DATABASE_USER"),
        'PASSWORD': env("DATABASE_PASSWORD"),
        'HOST': env("DATABASE_HOST"),
        'PORT': env("DATABASE_PORT"),
    }
}

So, you can define a default values as a follow:

SECRET_KEY = env("SECRET_KEY", default="unsafe-secret-key")
Note:

In your django project to add .env in your .gitignore also, it's advisable to create a .env.example with a template of all the variables required for the project.

I Hope It will help you....