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..
纠正这个问题最简单的方法是什么?提前致谢..
3 个解决方案
#1
19
Lakshman Prasad's answer is technically correct, but a bit cumbersome. A better way to escape text would be (as suggested in a comment by miku above):
Lakshman Prasad的答案在技术上是正确的,但有点麻烦。逃避文本的更好方法是(如上面miku的评论中所建议的):
from django.utils.html import escape
return HttpResponse(escape(some_string))
#2
5
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 |safe
filter:
要防止Django模板系统在模板中转义HTML,只需使用| safe过滤器:
response = "<img src='cats.png'/>"
# Meanwhile, in the template...
<div id="response">
{{response|safe}}
</div>
#3
1
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"""))
#1
19
Lakshman Prasad's answer is technically correct, but a bit cumbersome. A better way to escape text would be (as suggested in a comment by miku above):
Lakshman Prasad的答案在技术上是正确的,但有点麻烦。逃避文本的更好方法是(如上面miku的评论中所建议的):
from django.utils.html import escape
return HttpResponse(escape(some_string))
#2
5
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 |safe
filter:
要防止Django模板系统在模板中转义HTML,只需使用| safe过滤器:
response = "<img src='cats.png'/>"
# Meanwhile, in the template...
<div id="response">
{{response|safe}}
</div>
#3
1
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"""))