You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask+Firestore:获自动文档ID后render_template无法展示数据

解决方法

有两种简单的方式可以解决这个问题:

方式一:将文档ID嵌入数据字典,用列表传递

修改后端代码,把每个文档的ID加入对应的数据字典中,再存入列表:

donations = []
for doc in donation_ref.stream():
    donation_item = doc.to_dict()
    donation_item["doc_id"] = doc.id  # 添加文档ID字段
    donations.append(donation_item)

模板中遍历这个列表时,既能访问数据字段,也能拿到文档ID:

{% for ngo in donations %}
    <!-- 展示数据字段 -->
    <div>{{ ngo.your_field_name }}</div>
    <!-- 使用文档ID作为跳转参数 -->
    <a href="/edit/{{ ngo.doc_id }}">编辑</a>
    <a href="/delete/{{ ngo.doc_id }}">删除</a>
{% endfor %}

方式二:遍历字典的键值对

如果坚持使用字典存储数据,模板中遍历的时候要同时获取文档ID(键)和对应的数据(值),使用items()方法:

{% for doc_id, ngo in donations.items() %}
    <!-- 访问数据字段 -->
    <div>{{ ngo.your_field_name }}</div>
    <!-- 使用文档ID作为跳转参数 -->
    <a href="/edit/{{ doc_id }}">编辑</a>
    <a href="/delete/{{ doc_id }}">删除</a>
{% endfor %}

补充说明

你之前用{% for ngo in donations %}遍历字典时,默认只会遍历字典的键(也就是文档ID),所以无法访问数据字段。用items()可以同时拿到键和对应的值,或者改成列表形式把ID嵌入数据里,就能同时获取ID和字段内容。

内容的提问来源于stack exchange,提问作者Totta Zetterlund

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:33:17