如何在Django中根据Firestore文档数动态生成HTML表格行
问题描述
我在Firestore数据库中有一个文档集合,希望创建网页表单展示所有文档及其字段。目前我通过以下代码流式获取所有文档:
docs = db.collection(u'users').stream()
随后将所有文档ID存入列表,并按如下方式传递给HTML文件:
def index(request): myIDs =[] db = firestore.Client() docs = db.collection(u'users').stream() for doc in docs: myIDs.append(f'{doc.id}') return render(request, 'index.html', { "weight":"abc", "firstRow":myIDs[0], "secondRow":myIDs[1], "thirdRow":myIDs[2], "fourthRow":myIDs[3], "fifthRow":myIDs[4], "sixthRow":myIDs[5], "seventhRow":myIDs[6], })
之后编写了基础HTML代码来展示文档ID:
<html> <body> <table border="1" cellpadding = "5" cellspacing="5"> <tr> <td>{{ firstRow }}</td> <tr> <td>{{ secondRow }}</td> </tr> <tr> <td>{{ thirdRow }}</td> </tr> <tr> <td>{{ fourthRow }}</td> </tr> <tr> <td>{{ fifthRow }}</td> </tr> <tr> <td>{{ sixthRow }}</td> </tr> <tr> <td>{{ seventhRow }}</td> </tr> </tr> </table> </body> </html>
现在仅实现了基础功能,但作为Django和Python Web开发新手,想请教:如何让HTML行根据文档数量自适应生成?例如有20个文档时,自动生成20行并将每个文档ID对应到一行。
解决方案
1. 优化后端视图代码
无需手动拆分每个文档ID为单独变量,直接传递完整的ID列表到模板:
def index(request): myIDs =[] db = firestore.Client() docs = db.collection(u'users').stream() for doc in docs: myIDs.append(f'{doc.id}') return render(request, 'index.html', { "weight":"abc", "document_ids": myIDs # 传递整个ID列表 })
2. 前端模板动态生成行
利用Django模板的for循环标签,遍历列表自动生成对应行数的表格行:
<html> <body> <table border="1" cellpadding="5" cellspacing="5"> {% for doc_id in document_ids %} <tr> <td>{{ doc_id }}</td> </tr> {% endfor %} </table> </body> </html>
扩展:展示文档完整字段
如果需要展示文档的其他字段,后端可以传递包含ID和字段的字典列表:
def index(request): documents = [] db = firestore.Client() docs = db.collection(u'users').stream() for doc in docs: # 合并文档ID与字段数据 doc_data = doc.to_dict() doc_data['id'] = doc.id documents.append(doc_data) return render(request, 'index.html', { "weight":"abc", "documents": documents })
前端模板可添加表头和对应字段展示:
<html> <body> <table border="1" cellpadding="5" cellspacing="5"> <tr> <th>文档ID</th> <th>用户名</th> <!-- 替换为你的实际字段名 --> <th>邮箱</th> </tr> {% for doc in documents %} <tr> <td>{{ doc.id }}</td> <td>{{ doc.username }}</td> <td>{{ doc.email }}</td> </tr> {% endfor %} </table> </body> </html>
内容的提问来源于stack exchange,提问作者taha khamis
相关产品推荐
相关产品推荐

