【问题标题】:The context_instance argument of render_to_string is deprecated不推荐使用 render_to_string 的 context_instance 参数
【发布时间】:2016-04-07 22:03:05
【问题描述】:

我正在使用 Django 1.9。

使用render_to_string,我可以轻松地将呈现的 html 作为 json 传递给我的客户端脚本。但是,由于模板依赖user等变量,所以我还需要传递context_instance=RequestContext(request),否则模板将不知道request.user是什么,所以if语句中断等。

但是我收到了这个弃用警告:

RemovedInDjango110Warning:context_instance 参数 render_to_string 已弃用。 response_data['内容'] = render_to_string("profile/userprofile_detail/content.html", context, context_instance=RequestContext(request))

render_to_string 中传递RequestContext 的非弃用方式是什么?

【问题讨论】:

    标签: django


    【解决方案1】:

    render_to_string 有一个上下文参数,因此您可以像处理任何其他响应一样直接将其作为字典传递

    render_to_string(template_name, context=None, 
                     context_instance=_context_instance_undefined, request=None, using=None)
    

    链接的文档还包括鼓励这样做的说明

    自 1.8 版起已弃用:

    不推荐使用 context_instance 参数。使用上下文和如果需要的请求。

    【讨论】:

      【解决方案2】:

      推荐的方法是在调用render_to_string时传递request。然后,Django 将使用请求上下文呈现模板。

      render_to_string("profile/userprofile_detail/content.html", context, request=request)
      

      【讨论】:

      • 非常感谢!最后是适用于 Django 1.10+ 的东西。 :) 我相信这应该是正确的答案。
      猜你喜欢
      • 2016-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      • 2012-11-14
      • 2019-05-13
      • 1970-01-01
      相关资源
      最近更新 更多