如果我大约一半的 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/