问题描述
我已经到了一个点,我需要传递某些变量到我的所有观点(主要是自定义认证类型变量)。我被告知写自己的上下文处理器是最好的方法,但是我有一些问题。
我的设置文件看起来像这样
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'的模块,
看起来像
def say_hello(request):
return {
'say_hello':你好,
}
我是否可以假设我现在可以在我的意见中执行以下操作?
{{say_hello}}
现在,这在我的模板中无效。
我的看法看起来像
from django.shortcuts import render_to_response
pre>
def test(request):
return render_to_response(test.html)
解决方案您编写的上下文处理器应该可以工作。您是否认为问题是您的看法。
您是否肯定您的视图是使用
RequestContext
呈现?
例如:
def test_view(request):
return render_to_response('template.html')
上面的视图不会使用
TEMPLATE_CONTEXT_PROCESSORS
。确保您提供RequestContext
,如下所示:def test_view请求):
返回render_to_response('template.html',context_instance = RequestContext(请求))
I have come to a point where I need to pass certain variables to all of my views (mostly custom authentication type variables).
I was told writing my own context processor was the best way to do this, but I am having some issues.
My settings file looks like this
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", )
As you can see, I have a module called 'context_processors' and a function within that called 'say_hello'.
Which looks like
def say_hello(request): return { 'say_hello':"Hello", }
Am I right to assume I can now do the following within my views?
{{ say_hello }}
Right now, this renders to nothing in my template.
My view looks like
from django.shortcuts import render_to_response def test(request): return render_to_response("test.html")
解决方案The context processor you have written should work. The problem is in your view.
Are you positive that your view is being rendered with
RequestContext
?For example:
def test_view(request): return render_to_response('template.html')
The view above will not use the context processors listed in
TEMPLATE_CONTEXT_PROCESSORS
. Make sure you are supplying aRequestContext
like so:def test_view(request): return render_to_response('template.html', context_instance=RequestContext(request))
这篇关于在django中创建我自己的上下文处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!