python 在 Django 中,如何在 HttpResponse 中获得转义的 html?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1946281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:25:08  来源:igfitidea点击:

In Django, How do I get escaped html in HttpResponse?

pythondjangodjango-templatesescapinghttpresponse

提问by Nullpoet

The following code in one of my views returns unescaped html string which cannot be parsed in frontend since it is an Ajax request.

我的其中一个视图中的以下代码返回未转义的 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))

What is the simplest way to correct this ? Thanks in advance..

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

回答by Joel Cross

Lakshman Prasad's answer is technically correct, but a bit cumbersome. A better way to escapetext would be (as suggested in a comment by mikuabove):

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

from django.utils.html import escape
return HttpResponse(escape(some_string))

回答by Josh Hunt

To return just plain HTML to the client from within your view, use django.http.HttpResponse

要从视图中仅将纯 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)

To prevent the Django templating system from escaping HTML in a template, just use the |safefilter:

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

response = "<img src='cats.png'/>"

# Meanwhile, in the template...
<div id="response">
    {{response|safe}}
</div>

回答by Lakshman Prasad

It should escape by default.

它应该默认转义。

But, if you want to, you can explicitly force escaping.

但是,如果您愿意,您可以明确强制转义。

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