admin管理员组

文章数量:1289584

Here set environment variables using

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')

I want to display some values in UI. Is there any way to access values from DJANGO_SETTINGS_MODULE?

Here set environment variables using

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings')

I want to display some values in UI. Is there any way to access values from DJANGO_SETTINGS_MODULE?

Share Improve this question edited Jul 8, 2020 at 14:44 Zephyr 12.5k80 gold badges53 silver badges91 bronze badges asked Jul 8, 2020 at 14:37 Sineth LakshithaSineth Lakshitha 7136 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

You can pass variable you need in a context like that

import os

from django.shortcuts import render

def your_view(request):
    return render(request, 'path/to/template.html', context={
        'YOUR_ENV_VARIABLE': os.environ.get('YOUR_ENV_VARIABLE')
    })

And then in path/to/template.html you can access that context variable. But for JS files it can get a bit tricky, although you can use {{ template syntax }} to place your variable value inside <script> tag in HTML, but it is mon to have JS externally (linked from HTML). Then you can do something like that in your HTML.

<input id="YOUR_ENV_VARIABLE" value="{{ YOUR_ENV_VARIABLE }}" type="hidden" />

And then in your JS file

let hiddenInput = document.getElementById("YOUR_ENV_VARIABLE");
let yourEnvVariableValue = hiddenInput.value;

Edit: Accesing env variables without passing it to context

You can define your own template tags. Example:

# your_app/templatetags/env_extras.py

import os
from django import template

register = template.Library()


@register.simple_tag
def get_env_var(key):
    return os.environ.get(key)

And then in your HTML:

{% load env_extras %}

<input id="YOUR_ENV_VARIABLE" value="{% get_env_var 'YOUR_ENV_VARIABLE' %}" type="hidden" />

P.S. You might need to reload your server manually in order for custom tag to take effect.

本文标签: javascriptHow to access environment variable from html or js in DjangoStack Overflow