前面提到的问题中在表格中显示多个待办事项 是最后一个容易解决的问题。要编写一个新单元测试,检查模板是否也能显示多个待办事项:

lists/tests.py

    def test_displays_all_list_items(self):
        Item.objects.create(text='itemey 1')
        Item.objects.create(text='itemey 2')

        response = self.client.get('/')

        self.assertIn('itemey 1', response.content.decode())
        self.assertIn('itemey 2', response.content.decode())

运行测试和预期一样会失败

AssertionError: 'itemey 1' not found in '<html>\n <head>\n [...]
The Django template syntax has a tag for iterating through lists, {% for .. in ..
%}; 

Django的模板句法中有一个用于遍历列表的标签,即{% for .. in .. %};可以使用下面的方式使用这个标签:

        <table id="id_list_table">
            {% for item in items %}
                <tr><td>1: {{ new_item_text}}</td></tr>
            {% endfor %}
        </table>

 这是模板的主要优势之一,现在模板会在渲染多个<tr>行,每一行对应items变量中的一个元素。模板的魔力,可以阅读Django文档

只修改模板还不能让测试通过,还需要在首页的视图中把待办事项传入模板

def home_page(request):
    if request.method == 'POST':
        Item.objects.create(text=request.POST['item_text'])
        return redirect('/')

    items = Item.objects.all()
    return render(request,'home.html', {'items': items})

这样单元测试就能通过了。执行一下功能测试,能通过吗?

AssertionError: 'To-Do' not found in 'OperationalError at /'

很显然不能,要使用另一种功能测试调试技术,也是最直观的一种:手动访问网站。 http://localhost: 8000,会看见一个Django调试页面,提示“no such table: lists_item(没有这个表lists_item)”,一个很有帮助的调试信息,如图:

02-13 08:30