Django – 前端模版调用settings.py变量

2019年10月20日 作者 ruike

一、单个页面调用:

  • views调用setting,传递模版变量

views.py

from django.conf import settings


def my_view_function(request):
    context = {'favorite_color': settings.FAVORITE_COLOR}
    return render(request, 'template.html', context)

template.html

...
<a href="{{ favorite_color }}">path to admin media</a>
...

二、全局模版调用

希望在全局模版调用该变量时,可以使用上下文处理器

  • 在您的应用目录中创建文件context_processors.py
from django.conf import settings # import the settings file

def app_name(request):
    return {'APP_NAME': settings.APP_NAME}
  • 将上下文处理器添加到settings.py文件中:
TEMPLATES = [{
    # whatever comes before
    'OPTIONS': {
        'context_processors': [
            # whatever comes before
            "your_app.context_processors.app_name",
        ],
    }
}]
  • 在视图中使用可以在模板中添加的上下文处理器:
...
<title>{{ APP_NAME }}</title>
...