Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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.

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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',
                 ...
            ]
         }
      }
   ]
about 4 years ago · Santiago Trujillo Relatório

0

Extending on @vinay kumar's comment, you can create a custom template filter in the following way:

application/template_tags_folder/template_tags_file.py

from django.template.defaulttags import register
import os

@register.filter
def env(key):
    return os.environ.get(key, None)

And then in your template you can access it this way:

template.html

{% if 'DJANGO_SETTINGS_MODULE'|env == 'app_name.staging_settings' %}

Finally I leave a django docs reference and a stackoverflow reference for creating custom template tags and filters in django.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda