不推荐使用render_to_string的context_instance参数

时间:2016-04-07 22:03:05

标签: django

我正在使用Django 1.9。

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

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

  

RemovedInDjango110Warning:的context_instance参数   不推荐使用render_to_string。 response_data ['content'] =   render_to_string(“profile / userprofile_detail / content.html”,context,   context_instance = RequestContext的(请求))

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

2 个答案:

答案 0 :(得分:6)

render_to_string有一个上下文参数,所以你可以直接将它作为字典传递给任何其他响应

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

链接的文档还包括一个鼓励这个

的注释
  

自1.8版以来不推荐使用:

     

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

答案 1 :(得分:3)

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

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