现在,我需要将某些变量传递给我的所有视图(主要是自定义身份验证类型变量)。
有人告诉我,编写自己的上下文处理器是实现这一点的最好方法,但我遇到了一些问题。
我的设置文件如下所示
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages",
"sandbox.context_processors.say_hello",
)
如您所见,我有一个名为'context_processors‘的模块和一个名为'say_hello’的函数。
看起来像是
def say_hello(request):
return {
'say_hello':"Hello",
}
我假设我现在可以在我的视图中做以下事情,对吗?
{{ say_hello }}
现在,这在我的模板中呈现为空。
我的观点看起来像
from django.shortcuts import render_to_response
def test(request):
return render_to_response("test.html")
发布于 2010-05-24 06:23:58
您编写的上下文处理器应该可以工作。问题出在你的眼里。
您确信视图是用RequestContext
呈现的吗
例如:
def test_view(request):
return render_to_response('template.html')
上面的视图不会使用TEMPLATE_CONTEXT_PROCESSORS
中列出的上下文处理器。确保提供的RequestContext
如下所示:
def test_view(request):
return render_to_response('template.html', context_instance=RequestContext(request))
发布于 2018-03-20 08:02:00
从Django 1.8开始,您可以这样注册您的自定义上下文处理器:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'templates'
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'www.context_processors.instance',
],
},
},
]
假设您的上下文处理器位于context_processors.py
中的应用程序www
中
发布于 2015-02-11 15:36:56
如果您正在使用Django的render_to_response()
快捷方式用字典的内容填充模板,那么默认情况下将向您的模板传递一个上下文实例(而不是RequestContext
)。要在模板呈现中使用RequestContext
,请使用render()
快捷方式,该快捷方式与使用强制使用RequestContext
的context_instance
参数调用render_to_response()
相同。
https://stackoverflow.com/questions/2893724
复制相似问题