问题描述
我正在使用Django 1.9。
I'm using Django 1.9.
使用 render_to_string 我可以轻松地将渲染的html作为json传递给我客户端脚本。然而,由于模板依赖于诸如 user 的变量,我还需要传递 context_instance = RequestContext(request)否则模板将不知道什么 request.user 是,所以如果语句中断等。
With render_to_string I can easily pass rendered html as json to my clientside script. However, since the template rely on variables such as user, I need to also pass the context_instance=RequestContext(request), otherwise the template will not know what request.user is, so if statements break, etc.
但是我得到这个弃用警告:
However I am getting this deprecation warning:
在 render_to_string ?中通过 RequestContext / p>
What is the non-deprecated way to pass RequestContext in a render_to_string?
推荐答案
具有上下文参数,因此您可以直接将其作为字典传递,就像使用任何其他响应一样。
render_to_string has a context argument, so you can just pass it directly as a dictionary as you would with any other response
render_to_string(template_name, context=None, context_instance=_context_instance_undefined, request=None, using=None)
链接的文档还包含一个鼓励这个
The linked documentation also includes a note encouraging this
不建议使用context_instance参数。使用上下文和需要的请求。
The context_instance argument is deprecated. Use context and if needed request.
这篇关于render_to_string的context_instance参数已被弃用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!