Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access environment variables directly in a Django template?

I'm looking to do something like this non-working code in my Django template:

{% if os.environ.DJANGO_SETTINGS_MODULE == "settings.staging" %}

Is something like this possible? My workaround is creating a context processor to make the variable available across all templates, but wanted to know if there is a more direct way to achieve the same result.

like image 632
YPCrumble Avatar asked Apr 04 '17 12:04

YPCrumble


People also ask

How do you pass variables from Django view to a template?

How do you pass a Python variable to a template? And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file.

Where are environment variables stored in Django?

Environment variables live in the memory, not on the disk.


1 Answers

Use context_processor, do as below and you should be able to access os.environ['DJANGO_SETTINGS_MODULE'] as SETTING_TYPE in templates. Example you can use {% if SETTING_TYPE == "settings.staging" %}

project/context_processors.py

import os 

def export_vars(request):
    data = {}
    data['SETTING_TYPE'] = os.environ['DJANGO_SETTINGS_MODULE']
    return data

project/settings.py (your actual settings file)

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                 ...
                  'project.context_processors.export_vars',
                 ...
            ]
         }
      }
   ]
like image 88
rrmerugu Avatar answered Sep 30 '22 17:09

rrmerugu