【发布时间】:2016-07-13 22:12:12
【问题描述】:
在我的 Django 应用程序中,我需要通过 Ajax 调用刷新页面的一部分。关联的视图返回一个JsonResponse 对象,其中上下文中的一个键是重新渲染的 HTML。
类似这样的:
def myview(request):
...
tmpl8 = template.loader.get_template('page-table.html')
new_body = tmpl8.render({ 'rows': MyModel.custom_query() })
context = { 'new_body': new_body,
'other_info': other_information_for_javascript }
return JsonResponse(request, context)
现在,我还有添加通用信息的上下文处理器。其中一些在渲染page-table.html 时是需要的。
不幸的是,上下文处理器不会被纯 Template.render() 调用。它们在返回的 JsonResponse 对象上被调用,但是到那时已经太晚了,因为我已经渲染了模板。
在 Django 1.9 中,您可以将 RequestContext 提供给 Template.render 并且一切顺利 - 除了控制台中出现的弃用警告。 Django 1.10 坚持将Template.render 赋予dict。
所以,我能想到的最好的方法是:
from .context_processors import my_context_processor
def myview(request):
...
tmpl8 = template.loader.get_template('page-table.html')
render_context = { 'rows': MyModel.custom_query() }
render_context.update(my_context_processor(request))
new_body = tmpl8.render(render_context)
context = { 'new_body': new_body,
'other_info': other_information_for_javascript }
return JsonResponse(request, context)
基本上是显式调用处理器。
我错过了什么?
【问题讨论】:
标签: python django django-templates