zoukankan      html  css  js  c++  java
  • Django学习系列17:在模板中渲染待办事项

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

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

  • 相关阅读:
    wtforms
    day 036 线程 -创建,守护线程
    day 035 管道 和数据共享
    day034 锁,信号量,事件,队列,子进程与子进程通信,生产者消费者模型,joinableQueue
    day33 创建进程的方法和相关操作
    day 32并行 并发
    day 31 socketserver 和ftp打印进度条
    day 029 缓冲区和粘包 day 30 粘包的解决
    相关英语简称
    【实战】初识ListView及提高效率
  • 原文地址:https://www.cnblogs.com/ranxf/p/11691680.html
Copyright © 2011-2022 走看看