DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

3

django-environ with Lists Environment Varibles in .env Files

Issue

django-environ is the Python package that allows you to use Twelve-factor methodology to configure your Django application with environment variables.

It is very usefull package although there are some missing things in the documentation like how we use list as an environment variable?

They got doc for nested list but not for normal/raw list.

One of the main case for using list would be ALLOWED_HOSTS.

Let's assume we have hosts in our settings.py:

# settings.py
...

ALLOWED_HOSTS = [
    "example.com",
    "awesomedomain.com",
    "stagingdomain.com",
    "10.0.0.2",
    "198.162.44.72",
]
Enter fullscreen mode Exit fullscreen mode

How can we move this hardcoded list/array to an .env file and use it with django-environ?

Solution

First add env.list to your settings:

# settings.py
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")

Enter fullscreen mode Exit fullscreen mode

Then add your hosts with comma separated into .env which located in the root of your project or a proper location;

# .env
...

ALLOWED_HOSTS=example.com,awesomedomain.com,stagingdomain.com,10.0.0.2,198.162.44.72
Enter fullscreen mode Exit fullscreen mode

Extra

Your environment variables file —.env, can be anything and anywhere —.envs/.local, .env.prod, as long as you configure it properly in your settings:

# settings.py
import os

import environ

# Set the project base directory
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Initiate related env class
env = environ.Env()
# Take environment variables from .env.dev file
environ.Env.read_env(os.path.join(BASE_DIR, '.env.dev')

...
Enter fullscreen mode Exit fullscreen mode

All done!

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay