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 resides and add the following key-value pair inside the file.

Step 3 : Update

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

import environ

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

# Raises django's ImproperlyConfigured exception if SECRET_KEY not in os.environ

    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': env("DATABASE_NAME"),
        'USER': env("DATABASE_USER"),
        '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")

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....