Django模板循环问题:如何在HTML表格展示sum_list全部条目?
解决Django表格仅显示单条数据的问题
我来帮你搞定这个问题!你现在只显示一条数据的原因有两个,咱们一步步修正:
问题根源
- Views.py中的对象复用问题:你一直在循环里复用同一个
detail实例,每次循环都会覆盖它的customer和qty属性,最后传给模板的detail只保留了最后一条数据。 - HTML未使用循环遍历:模板里只写了单个行的渲染,没有用Django模板的
for循环来遍历整个列表。
修正步骤
1. 修正views.py代码
你有两种选择,选其中一种就行:
方案一:直接传递sum_list(更简单)
去掉循环赋值的代码,直接把整理好的sum_list传给模板:
# 替换原来的for循环和return语句 # for i,j in sum_list: # detail.customer = i # detail.qty = j return render(request,'index.html', {'sum_list': sum_list})
方案二:传递模型对象列表(如果需要用Sale_detail模型)
每次循环创建新的Sale_detail实例,存入列表后传给模板:
detail_list = [] for i,j in sum_list: detail = Sale_detail() # 每次循环新建实例,避免覆盖 detail.customer = i detail.qty = j detail_list.append(detail) return render(request,'index.html', {'detail_list': detail_list})
2. 修正HTML模板代码
根据你选的方案,对应修改HTML:
如果用方案一(sum_list)
用{% for %}循环遍历列表,forloop.counter用来生成序号:
<table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">Customer</th> <th scope="col">Quantity (MT)</th> </tr> </thead> <tbody> {% for item in sum_list %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ item.0 }}</td> <!-- 取列表第一个元素:客户名 --> <td>{{ item.1 }}</td> <!-- 取列表第二个元素:数量 --> </tr> {% endfor %} </tbody> </table>
如果用方案二(detail_list)
遍历对象列表,直接调用对象属性:
<table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">Customer</th> <th scope="col">Quantity (MT)</th> </tr> </thead> <tbody> {% for detail in detail_list %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ detail.customer }}</td> <td>{{ detail.qty }}</td> </tr> {% endfor %} </tbody> </table>
这样修改后,表格就能显示sum_list里的所有条目啦!
内容的提问来源于stack exchange,提问作者Lovepreet Singh
相关产品推荐
相关产品推荐

