循环不向表中添加数据

时间:2018-03-18 19:31:43

标签: python django

for循环有效,但不是将数据添加到表中,而是将数据添加到现有表下。

laptop_list.html

<div class="container">
      <div class="table-responsive-sm">
      <table class="table">
     {%for laptop in laptops%}
    <div class="table-responsive-sm">
        <tbody>
          <tr>
            <td>{{laptop.laptop_id}}</td>
            <td>{{laptop.make}}</td>
            <td>{{laptop.model}}</td>
            <td>{{laptop.specification}}</td>
            <td>{{laptop.warranty}}</td>
            <td>{{laptop.condition}}</td>
            <td>{{laptop.price}}</td>
          </tr>
        </tbody>
      </div>
      </table>
      {%endfor%}
      </div>

    </div>

models.py

class Laptop(models.Model):
    make = models.CharField(max_length = 100)
    model = models.CharField(max_length = 100)
    specification = models.CharField(max_length = 100)
    warranty = models.CharField(max_length = 100)
    condition = models.CharField(max_length = 100)
    price = models.CharField(max_length = 100)
    added_by = models.ForeignKey(User, default = None, on_delete=models.CASCADE)

views.py

def laptop_list(request):
    laptops = Laptop.objects.all()
    return render(request,'laptops/laptop_list.html',{'laptops':laptops})

1 个答案:

答案 0 :(得分:3)

这里有一些错误。

您不能将div作为表元素的子元素。您应该删除表中的重复table-responsive-sm div。

此外,该表应该只有一个tbody元素。 tbody应该在for循环之外。

所以:

<div class="container">
  <div class="table-responsive-sm">
    <table class="table">
      <tbody>
        {% for laptop in laptops %}
          <tr>
            <td>{{laptop.laptop_id}}</td>
            <td>{{laptop.make}}</td>
            <td>{{laptop.model}}</td>
            <td>{{laptop.specification}}</td>
            <td>{{laptop.warranty}}</td>
            <td>{{laptop.condition}}</td>
            <td>{{laptop.price}}</td>
          </tr>
        {% endfor %}
      </tbody>
    </table>
  </div>
</div>