[英]Django, template context processors
I have a weird problem, I want to add a global query using context processors. 我有一个奇怪的问题,我想使用上下文处理器添加一个全局查询。 This is how I did it by following : 这就是我通过以下方式做到的:
made a processor.py in my app as such: 在我的应用程序中制作了processor.py:
from myproject.myapp.models import Foo
def foos(request):
return {'foos': Foo.objects.all()}
and at the end of my setting.py I have added this: 在我的setting.py结束时我添加了这个:
TEMPLATE_CONTEXT_PROCESSORS = ('myapp.processor.foos',)
Lastly I pass my view as this: 最后我传递了我的观点:
def index_view(request):
return render_to_response('index.html', {}, context_instance=RequestContext(request))
and at my index.html template: 在我的index.html模板:
<select id="select_foo">
{% for foo in foos %}
<option value="/{{ foo.slug }}">{{ foo.name }}</option>
{% endfor %}
</select>
And lastly my url: 最后我的网址:
(r'^$', 'myapp.views.index_view'),
My foos display without any problem, however my media_url and other contexts are gone. 我的foos显示没有任何问题,但我的media_url和其他上下文已经消失。 What can be the issue 可能是什么问题
You need to add the default values of TEMPLATE_CONTEXT_PROCESSORS. 您需要添加TEMPLATE_CONTEXT_PROCESSORS的默认值。 However, instead of hard-coding those values, which will be tied to a specific version of Django, you can append your context processor to the default values by the following: 但是,您可以通过以下方式将上下文处理器附加到默认值,而不是硬编码那些与特定版本的Django相关联的值。
from django.conf import global_settings
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
"myapp.processor.foos",
)
Make sure to include the trailing comma in the tuple, so that Python recognizes it as a tuple. 确保在元组中包含尾随逗号,以便Python将其识别为元组。
When you specify this: 当你指定这个:
TEMPLATE_CONTEXT_PROCESSORS = ('myapp.processor.foos',)
In your settings file, you are overriding the Django's default context processors . 在您的设置文件中,您将覆盖Django的默认上下文处理器 。 In order to extend the list, you need to include the default ones in your settings: 要扩展列表,您需要在设置中包含默认列表:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.core.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"myapp.processor.foos",
)
Note, the settings above are the defaults (plus your processor) for django 1.1. 注意,上面的设置是django 1.1的默认设置(加上你的处理器)。
Here what worked for me for Django 1.3 这对Django 1.3来说对我有用
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.core.context_processors.static",
"django.contrib.messages.context_processors.messages",
"myapp.processor.foos", )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.