2

我试图使用 Django 的自动转义功能,并且由于它没有按预期工作。下面是代码,我尝试了 autoescape 甚至 ESCAPE 功能..

在表格中输入名称 - <i>Jacob</i>

预期产出 -&lt;i&gt;Jacob&lt;/i&gt;

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

1 回答 1

0

使用cgi.escape功能:

前任:

import cgi
cgi.escape('<i>Jacob</i>')
>>>'&lt;i&gt;Jacob&lt;/i&gt;'

在你的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)
于 2013-11-07T16:12:47.513 回答