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

Flask Jinja模板遍历Python国家代码字典无输出及报错求解

问题根源

  1. 后端视图代码存在两处逻辑错误:
    • 循环内每次重复初始化countriess = {},会清空之前存储的国家数据,最终仅保留最后一个国家的键值对
    • 最终传入模板的countries是单个字典对象,和你参考的遍历「字典列表」的教程结构不匹配
  2. 模板遍历逻辑和传入数据结构不符:
    你用了遍历字典列表的两层循环,而遍历单个字典时,for dict_item in countries默认遍历的是字典的键(字符串类型,比如AF),自然调用items属性会抛出字符串无该属性的报错。

解决方法

提供两种可直接落地的方案,二选一即可:

方案1:适配参考教程的字典列表结构

修改views.py的循环逻辑,将所有国家存为字典列表:

@views.route("/test", methods=["GET"])
@login_required
def test():
    countries = Country.query.all()
    # 初始化列表存储所有国家字典
    countriess = []
    for country in countries:
        country_dict = {}
        country_dict[country.country_code] = country.country_name
        countriess.append(country_dict)
    return render_template("TEST.html", user=current_user, countries=countriess)

模板代码保持原有两层循环即可,注意Jinja2中调用字典的items不需要加括号:

{% for dict_item in countries %}
    {% for key,value in dict_item.items %}
        <h1>Key: {{ key }}</h1>
        <h2>Value: {{ value }}</h2>
    {% endfor %}
{% endfor %}

方案2:用单个字典存储所有国家,简化模板逻辑

这种方案更简洁,不需要嵌套循环:
修改views.py逻辑,用单个字典存储所有国家代码和名称的映射:

@views.route("/test", methods=["GET"])
@login_required
def test():
    countries = Country.query.all()
    # 初始化字典存储所有国家映射
    countriess = {}
    for country in countries:
        countriess[country.country_code] = country.country_name
    return render_template("TEST.html", user=current_user, countries=countriess)

模板直接一层循环遍历字典即可:

{% for key,value in countries.items %}
    <h1>Key: {{ key }}</h1>
    <h2>Value: {{ value }}</h2>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:54:04