Django,模板上下文处理器 [英] Django, template context processors

查看:112
本文介绍了Django,模板上下文处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,我想使用上下文处理器添加一个全局查询。
这是我如何通过以下



在我的应用程序中制作了一个processor.py:

  from myproject.myapp.models import Foo 

def foos(request):
return {'foos':Foo.objects.all()}

在我的setting.py结尾我添加了这个:

  TEMPLATE_CONTEXT_PROCESSORS =('myapp.processor.foos',)

最后我通过我的观点:

  def index_view(request):

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

和我的index.html模板:

 < select id =select_foo> 
{%foos in foos%}
< option value =/ {{foo.slug}}> {{foo.name}}< / option>
{%endfor%}
< / select>

最后我的网址:

 (r'^ $','myapp.views.index_view'),

我的foos显示没有任何问题,但是我的media_url和其他上下文消失了。
可能是什么问题

解决方案

当您指定时:

  TEMPLATE_CONTEXT_PROCESSORS =('myapp.processor.foos',)

在您的设置文件中,您将覆盖Django的默认上下文处理器。为了扩展列表,您需要在设置中包含默认值:

  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,

注意,上面的设置是django 1.1的默认设置(加上处理器)。


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:

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:

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:

<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. What can be the issue

解决方案

When you specify this:

TEMPLATE_CONTEXT_PROCESSORS = ('myapp.processor.foos',)

In your settings file, you are overriding the Django's default context processors. 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,模板上下文处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆