【问题标题】:Context processors and manual rendering上下文处理器和手动渲染
【发布时间】: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


    【解决方案1】:

    让我们看看render 文档是怎么说的:

    Template.render(context=None, request=None)
    呈现此模板 具有给定的上下文。

    如果提供了上下文,它必须是一个字典。如果未提供,则 引擎将使用空上下文呈现模板。

    如果提供了请求,它必须是一个 HttpRequest。然后发动机 必须使其以及 CSRF 令牌在模板中可用。 如何实现这一点取决于每个后端。

    这是搜索算法的一个示例。对于这个例子 模板设置为:

    第二个参数是请求!所以我们有

     new_body = tmpl8.render(render_context, request)
    

    【讨论】:

      【解决方案2】:

      尝试将request 传递给render() 方法:

      new_body = tmpl8.render({ 'rows': MyModel.custom_query() }, request)
      

      【讨论】:

        猜你喜欢
        • 2021-11-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-08
        相关资源
        最近更新 更多