我试图使用Django的autoescape功能,因为它没有按预期工作。下面是代码,我尝试了autoescape甚至是ESCAPE功能..
输入表单的名称 - <i>Jacob</i>
预期输出 - <i>Jacob</i>
html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test Page</title>
</head>
<body>
This is a test page
{% if display_form %}
<form action="." method="post">{% csrf_token %}
FIRST NAME : <input type="text" name="fname">
<input type="submit" value="register"/>
</form>
{% else %}
{% autoescape on %}
{{ firstname|escape }}
{% endautoescape %}
{% endif %}
</body>
</html>
views.py
def test_page(request):
print 'request.method =', request.method
if request.method == 'POST':
print 'request.post = ', request.POST['fname']
variables = RequestContext(request,{'display_form':False,'firstname':request.POST['fname']})
return render_to_response('test_page.html',variables)
else:
variables = RequestContext(request,{'display_form':True})
return render_to_response('test_page.html',variables)
答案 0 :(得分:0)
使用cgi.escape
功能:
例如:
import cgi
cgi.escape('<i>Jacob</i>')
>>>'<i>Jacob</i>'
在views.py
import cgi
def test_page(request):
print 'request.method =', request.method
if request.method == 'POST':
print 'request.post = ', request.POST['fname']
variables = RequestContext(request,{'display_form':False,'firstname':cgi.escape(request.POST['fname'])})
return render_to_response('test_page.html',variables)
else:
variables = RequestContext(request,{'display_form':True})
return render_to_response('test_page.html',variables)