Nul*_*oet 10 python django escaping httpresponse django-templates
我的一个视图中的以下代码返回未转义的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))
Run Code Online (Sandbox Code Playgroud)
纠正这个问题最简单的方法是什么?提前致谢..
Joe*_*oss 22
Lakshman Prasad的答案在技术上是正确的,但有点麻烦.逃避文本的更好方法是(如上面miku的评论中所建议的):
from django.utils.html import escape
return HttpResponse(escape(some_string))
Run Code Online (Sandbox Code Playgroud)
要从视图中返回纯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)
Run Code Online (Sandbox Code Playgroud)
要防止Django模板系统在模板中转义HTML,只需使用|safe过滤器:
response = "<img src='cats.png'/>"
# Meanwhile, in the template...
<div id="response">
{{response|safe}}
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13566 次 |
| 最近记录: |