如何在Django模板中传递Sportsipy Python体育API数据
Fixing "Object not iterable" Error with Sportsipy Boxscores in Django Templates
你遇到的问题根源很明确:你传递给Django模板的是Boxscores类的实例对象,而不是里面可迭代的比赛数据集合。
看你的代码,games_today = Boxscores(datetime.today())创建的是一个sportsipy.ncaab.boxscore.Boxscores实例——这个对象本身不是可迭代的容器,所以模板里的{% for game in games_today %}会直接抛出"不可迭代"的错误。而你在终端能正常打印games_today.games,是因为这个属性才是存储比赛数据的核心字典(键为日期字符串,值为对应日期的比赛列表)。
解决方案:传递正确的数据给模板
修改你的视图代码,把games_today.games(而非整个实例)放到上下文里:
from django.shortcuts import render from datetime import datetime from sportsipy.ncaab.boxscore import Boxscores def games(request): """ View to return index page """ # 格式化日期为YYYY-MM-DD,确保和API返回的日期格式匹配 today_date = datetime.today().strftime('%Y-%m-%d') games_today = Boxscores(today_date) # 传递可迭代的games字典,而非Boxscores实例 context = { 'games_today': games_today.games } return render(request, 'games/games.html', context)
调整模板代码适配数据结构
因为games_today.games是一个日期为键、比赛列表为值的字典,模板需要先遍历日期分组,再遍历每个分组下的比赛:
{% for date, game_list in games_today.items %} <h2 class="white">Games on {{ date }}</h2> {% for game in game_list %} <div class="game-item"> <p class="white">Home Team: {{ game.home_team }}</p> <p class="white">Away Team: {{ game.away_team }}</p> <p class="white">Score: {{ game.away_score }} - {{ game.home_score }}</p> </div> {% empty %} <p class="white">No games scheduled for today.</p> {% endfor %} {% endfor %}
为什么转JSON没解决问题?
你之前尝试转JSON无效,大概率是因为错误序列化了整个Boxscores实例,而非里面的games属性。而且直接传递Python原生的数据结构(字典+列表)给Django模板,比转成JSON再解析要更简洁高效。
额外提示
如果发现games_today.games为空,检查你传递给Boxscores的日期格式——Sportsipy的API通常期望YYYY-MM-DD格式的字符串,用strftime('%Y-%m-%d')格式化日期能避免格式不匹配的问题。
内容的提问来源于stack exchange,提问作者Ryan Thomas
相关产品推荐
相关产品推荐

