什么时候适合使用Django上下文处理器? [英] When is it appropriate to use Django context processors?

查看:108
本文介绍了什么时候适合使用Django上下文处理器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果大约一半的视图需要相同的数据集,那么使用上下文处理器来使数据总是可用,还是有更好的方法来避免重复代码以跨多个视图获取数据,而无需查询数据是否不会在视图中使用?

If about half of my views require the same data set, is it appropriate to use a context processor to make the data always available, or is there a better way to avoid repeating the code to get that data across several views without querying the data if it won't be used in the view?

推荐答案

RequestContext initializer将运行设置文件中列出的任何上下文处理器,但它还需要运行其他处理器的列表。任何通用上下文处理器都可以放在settings.py中,更具体的可以根据具体情况添加到 RequestContext 中。

The RequestContext initializer will run any context processors listed in the settings file, but it also takes a list of additional processors to run. Any general purpose context processors can be put in settings.py and more specific ones can be added to the RequestContext on a case-by-case basis.

离开 RequestContext 完全不运行任何上下文处理器。

Leave RequestContext out altogether to not run any context processors.

# want context processors listed in settings.py as well as some more specific ones
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request, processors = extra_processors))

# want only context processors listed in settings.py
return render_to_response('template.html', {'foo':'bar'}, context_instance=RequestContext(request))

# no context processors
return render_to_response('template.html', {'foo':'bar'})

这篇关于什么时候适合使用Django上下文处理器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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