【问题标题】:How do I modify the HttpResponse object in django?如何在 django 中修改 HttpResponse 对象?
【发布时间】:2009-12-22 13:34:51
【问题描述】:

我需要转义使用 render_to_response 返回的 html。 我找不到任何合适的文档。有人可以指出某个方向吗?

代码是:

return render_to_response(template_name, {return render_to_response(template_name, {
            'form': form,
            redirect_field_name: redirect_to,
            'site': current_site,
            'site_name': current_site.name,
        }, context_instance=RequestContext(request))

这里我需要对响应 html 文本进行转义。 我知道正在读取字符串中的模板文件并使用 re.escape() 对其进行转义然后渲染它。 有什么更清洁、更简单的方法吗??

【问题讨论】:

    标签: django django-templates escaping httpresponse


    【解决方案1】:

    默认情况下,通过render_to_response 从视图传递到模板的字符串被转义。

    见:http://docs.djangoproject.com/en/dev/topics/templates/#id2

    默认情况下,在 Django 中,每个模板都会自动转义每个变量标签的输出。具体来说,这五个字符被转义了:

    < is converted to &lt;
    > is converted to &gt;
    ' (single quote) is converted to &#39;
    " (double quote) is converted to &quot;
    & is converted to &amp;
    

    再次强调,此行为默认开启。

    【讨论】:

      【解决方案2】:

      听起来您希望整个响应都被转义——这是真的吗?这似乎有点奇怪,但你当然可以做到。

      import django.utils.html as html
      string = render_to_string(<all of the args to render_to_response>)
      escaped_string = html.escape(string)
      return HttpResponse(escaped_string)
      

      我不太确定另一端的人/浏览器会做什么,但这听起来像你所要求的。

      【讨论】:

        【解决方案3】:

        您可以使用escape 模板过滤器或autoescape 模板标签。见http://docs.djangoproject.com/en/dev/ref/templates/builtins/

        【讨论】:

          猜你喜欢
          • 2013-07-21
          • 1970-01-01
          • 1970-01-01
          • 2010-12-10
          • 1970-01-01
          • 1970-01-01
          • 2021-10-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多