如何在Django视图中将元组列表传递至模板以单独迭代每个数据成员
解决Django传递PostgreSQL查询结果到模板并生成表格的问题
1. 将查询数据传递给模板
你当前的代码已经通过cur.fetchall()获取到了元组列表rows,但没有把这个数据传递给模板,导致模板无法访问这些内容。需要修改render方法,把rows作为上下文参数传入:
修改后的views.py代码:
def search_owner_prop(request): if request.method == 'POST': o_no = request.POST.get('owner_num') conn = psycopg2.connect(database="dreamhomeproperty", user="postgres", password="****", host="*****", port="****") cur = conn.cursor() # 改用参数化查询,避免**SQL注入**风险 cur.execute(''' SELECT property_for_rent.property_n, private_owner.fname, property_for_rent.street, property_for_rent.rooms, property_for_rent.typee FROM dreamhome_schema.property_for_rent INNER JOIN dreamhome_schema.private_owner ON property_for_rent.owner_number = %s AND private_owner.owner_no = %s ''', (o_no, o_no)) rows = cur.fetchall() conn.close() # 将查询结果传入模板 return render(request, 'owner_with_prop.html', {'property_data': rows}) else: return render(request, 'search_owner_prop.html')
2. 在模板中遍历数据生成HTML表格
在owner_with_prop.html模板里,使用Django模板语法遍历property_data这个元组列表,逐个取出元组内的元素填充到表格中:
<table border="1"> <thead> <tr> <th>物业编号</th> <th>业主姓名</th> <th>街道</th> <th>房间数</th> <th>物业类型</th> </tr> </thead> <tbody> {% for item in property_data %} <tr> <td>{{ item.0 }}</td> <!-- 对应SELECT的第一个字段property_n --> <td>{{ item.1 }}</td> <!-- 对应第二个字段fname --> <td>{{ item.2 }}</td> <!-- 对应第三个字段street --> <td>{{ item.3 }}</td> <!-- 对应第四个字段rooms --> <td>{{ item.4 }}</td> <!-- 对应第五个字段typee --> </tr> {% empty %} <tr> <td colspan="5">未找到匹配的物业信息</td> </tr> {% endfor %} </tbody> </table>
重要提醒
绝对不要用f-string拼接SQL语句,这会引发严重的SQL注入漏洞。上面的代码采用了psycopg2标准的参数化查询方式,用%s作为占位符,参数通过元组传递,这是安全的写法。
内容的提问来源于stack exchange,提问作者Hassan Ali
相关产品推荐
相关产品推荐

