django - 什么时候适合使用 Django 上下文处理器?

标签 django django-templates

如果我大约一半的 View 需要相同的数据集,是否适合使用上下文处理器使数据始终可用,或者是否有更好的方法来避免重复代码以跨多个 View 获取数据而无需查询数据它不会在 View 中使用?

最佳答案

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

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

# 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 - 什么时候适合使用 Django 上下文处理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/831301/

相关文章:

python - 如何修改此正则表达式以在 Django 中接受此 URL?

python - HTML for ul 元素内的循环

python-3.x - 如何将计算变量添加到 wagtail StructBlock 模板上下文中?

python - 在django模板中对forloop.counter进行加法运算

django - 在测试期间禁用特定的 Django 中间件

django - 使用 prefetch_related 仅获取关系的特定条目

django - Django 中的 render() 和 redirect() 有什么区别?

python - django treebeard MP_Node Tree 对象的多个版本(修订版)

html - 如何访问 CSS 中的媒体文件? Django

django & "TemplateDoesNotExist"错误