【问题标题】:In Django, How do I get escaped html in HttpResponse?在 Django 中,如何在 HttpResponse 中获得转义的 html?
【发布时间】:2010-12-29 02:40:41
【问题描述】:

我的一个视图中的以下代码返回未转义的 html 字符串,由于它是 Ajax 请求,因此无法在前端进行解析。

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))

纠正这个问题的最简单方法是什么? 提前谢谢..

【问题讨论】:

    标签: python django django-templates escaping httpresponse


    【解决方案1】:

    要从您的视图中仅将纯 HTML 返回给客户端,请使用 django.http.HttpResponse

    from django.http import HttpResponse
    
    def view(request)
        # Do stuff here
        output = '''
        <html>
            <head>
                <title>Hey mum!</title>
            </head>
        </html>'''
        return HttpResponse(output)
    

    要防止 Django 模板系统在模板中转义 HTML,只需使用 |safe 过滤器:

    response = "<img src='cats.png'/>"
    
    # Meanwhile, in the template...
    <div id="response">
        {{response|safe}}
    </div>
    

    【讨论】:

    • Django 没有自动转义我使用 firebug 确认的响应。我需要它被逃脱。
    • 那么,您希望&amp;lt;p&amp;gt; 更改为&amp;lt;p&amp;gt;?还是保持&amp;lt;p&amp;gt;
    【解决方案2】:

    它应该默认转义。

    但是,如果您愿意,您可以显式强制转义。

    from django.utils.safestring import mark_for_escaping
    return HttpResponse(mark_for_escaping(loader.render_to_string(""""Render Response Syntax"""))
    

    【讨论】:

      【解决方案3】:

      Lakshman Prasad 的回答在技术上是正确的,但有点麻烦。 转义文本的更好方法是(如上面 miku 的评论中所建议的):

      from django.utils.html import escape
      return HttpResponse(escape(some_string))
      
      猜你喜欢
      • 2020-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2011-01-06
      • 2015-10-06
      • 1970-01-01
      • 2022-01-10
      相关资源
      最近更新 更多