fly*_*zai 7 python django html5
我正在编写我的第一个Django
应用程序,跟着这本书:
在书中有一个测试,验证html是否按预期返回.这是测试:
def test_home_page_returns_correct_html(self):
request = HttpRequest()
response = home_page(request)
expected_html = render_to_string('home.html')
print(expected_html)
print(response.content.decode())
self.assertEqual(response.content.decode(), expected_html)
Run Code Online (Sandbox Code Playgroud)
我的测试在测试中失败,assertEqual
因为我csrf token
在我的HTML中添加了一个Django Template Language
.这是我的HTML页面的样子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
{% csrf_token %}
</form>
<table id="id_list_table">
<tr><td>{{ new_item_list }}</td></tr>
</table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
由于render_to_string
方法不包括令牌,我的断言失败.以下是print
我的测试中包含的两个陈述:
F<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
</form>
<table id="id_list_table">
<tr><td></td></tr>
</table>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do lists</title>
</head>
<body>
<h1>Your To-Do list</h1>
<form method="POST">
<input name="item_text" id="id_new_item" placeholder="Enter a to-do item"/>
<input type='hidden' name='csrfmiddlewaretoken' value='VAiGvXZLHCjxWEWdjhgQRBwBSnMVoIWR' />
</form>
<table id="id_list_table">
<tr><td></td></tr>
</table>
</body>
</html>
F.
Run Code Online (Sandbox Code Playgroud)
他在书中没有这个问题(他正在使用1.8
),所以我想知道方法行为是否已经改变,或者我是如何写这个测试来通过的.
该request
论点被添加到render_to_string
Django 1.8中.您可以尝试将测试中的行更改为:
expected_html = render_to_string('home.html', request=request)
Run Code Online (Sandbox Code Playgroud)
它只需要在Django 1.9+中进行此更改,测试在没有Django 1.8请求的情况下通过.
归档时间: |
|
查看次数: |
1712 次 |
最近记录: |