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

将字典值渲染到HTML出错:Django多城市天气数据无法显示

Django多城市天气数据无法渲染到模板的问题排查与修复

核心问题分析

  1. 循环覆盖数据,未保留所有城市信息
    原代码在for循环中每次都给data变量重新赋值,循环结束后data仅保留最后一个城市的天气数据,且是单个字典结构,无法支撑模板遍历所有城市的需求。

  2. 模板遍历逻辑错误
    模板中试图遍历单个字典data,此时遍历的是字典的key值;同时直接使用{{ country_code }}这类变量,Django模板无法识别这些变量属于哪个城市的信息,自然无法正确渲染。


修正后的代码

views.py

from django.shortcuts import render
import urllib.request
import json

def display(request):
    cities = ['vijayawada','guntur','tenali','rajahmundry','amaravathi']
    weather_list = []  # 用列表存储所有城市的天气数据
    for city in cities:
        source = urllib.request.urlopen(
            f'https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid=5980455dc827c861d5ac4125c3673b43').read()
        list_of_data = json.loads(source)

        city_data = {
            "country_code": str(list_of_data['sys']['country']),
            "coordinate": f"{list_of_data['coord']['lon']}, {list_of_data['coord']['lat']}",
            "temp": f"{list_of_data['main']['temp']} °C",
            "pressure": str(list_of_data['main']['pressure']),
            "humidity": str(list_of_data['main']['humidity']),
            'main': str(list_of_data['weather'][0]['main']),
            'description': str(list_of_data['weather'][0]['description']),
            'icon': list_of_data['weather'][0]['icon'],
            'city_name': city  # 新增城市名,方便模板展示
        }
        weather_list.append(city_data)
        print(city_data)
    
    # 将多城市数据列表传入模板上下文
    return render(request, "display.html", {"weather_data": weather_list})

display.html

<html>
<head>
    <title>API Display</title>
    <style>
        .city-weather {
            margin: 15px 0;
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <h1>Weather details</h1>
    {% for city_info in weather_data %}
    <div class="city-weather">
        <h3>{{ city_info.city_name }}</h3>
        <p>国家代码: {{ city_info.country_code }}</p>
        <p>坐标: {{ city_info.coordinate }}</p>
        <p>气温: {{ city_info.temp }}</p>
        <p>气压: {{ city_info.pressure }} hPa</p>
        <p>湿度: {{ city_info.humidity }}%</p>
        <p>天气状况: {{ city_info.main }} - {{ city_info.description }}</p>
        <img src="http://openweathermap.org/img/w/{{ city_info.icon }}.png" alt="{{ city_info.description }}">
    </div>
    {% empty %}
    <p>暂无天气数据</p>
    {% endfor %}
</body>
</html>

修正说明

  1. 新增weather_list列表存储所有城市的天气数据,避免循环中覆盖数据。
  2. 模板上下文传递多城市数据列表,让模板可以遍历所有城市信息。
  3. 模板中通过city_info.key的方式访问单个城市的具体数据,同时新增样式和天气图标,优化展示效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 06:31:01