码迷,mamicode.com
首页 > 其他好文 > 详细

Django学习系列17:在模板中渲染待办事项

时间:2019-10-17 15:47:09      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:test   检查   objects   inf   ima   ==   nta   还需   sse   

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

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: {{ 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)”,一个很有帮助的调试信息,如图:

技术图片

 

Django学习系列17:在模板中渲染待办事项

标签:test   检查   objects   inf   ima   ==   nta   还需   sse   

原文地址:https://www.cnblogs.com/ranxf/p/11691680.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!