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
:
...
ALLOWED_HOSTS = [
"example.com",
"awesomedomain.com",
"stagingdomain.com",
"10.0.0.2",
"198.162.44.72",
]
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
:
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")
Then add your hosts with comma separated into .env
which located in the root of
your project or a proper location;
...
ALLOWED_HOSTS=example.com,awesomedomain.com,stagingdomain.com,10.0.0.2,198.162.44.72
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')
...
All done!