gpt4 book ai didi

python - 在应用程序模板中启用上下文处理器

转载 作者:太空宇宙 更新时间:2023-11-03 16:29:01 25 4
gpt4 key购买 nike

我的 Django 项目中有一些应用程序具有自己的模板(即 /project/app1/template/project/app2/template 等)。

但是,模板上下文处理器(在主应用/项目的 settings.py 中定义)在这些应用模板中不可用。

我必须手动设置 context_instance 才能在子模板中启用上下文处理器(否则模板中会缺少上下文处理器):

from django.template import RequestContext

def index(request):
return render_to_response('index.html', {}, context_instance=RequestContext(request))

这是我的settings.py:

PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
BASE_DIR = PACKAGE_ROOT


TEMPLATES = [
{
"DIRS": [
os.path.join(PACKAGE_ROOT, "templates"),
],
"APP_DIRS": True,

"OPTIONS": {
...
"context_processors": [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.request",
...
],
},
},
]

如何在不手动在每个 View 函数中注入(inject) context_instance 的情况下访问应用模板中的上下文处理器?

最佳答案

这与“应用模板”完全无关;无论您的模板位于何处,行为都是完全相同的。

如果你想运行上下文处理器,你总是需要一个RequestContext;除此之外,那是因为它们传递了请求对象,所以它需要存在。

但是有一个快捷方式可以创建该请求上下文,那就是 render 函数:

def index(request):
return render(request, 'index.html', {})

请注意,这将请求作为第一个参数。

关于python - 在应用程序模板中启用上下文处理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37768046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com