我正在从我在模板中循环的 API 接收数据。每个值都很好,但日期。
因为模板不能将日期格式化为字符串,所以我在我的视图中对其进行了格式化(如下所示)。但是现在当我将该日期时间变量传递到我的模板中时,它只为每次迭代显示相同的日期,其他所有值都是正确的。
如何正确迭代日期?
谢谢!
for game in games:
date = game['schedule']['date']
datetime_date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ')
game_date = datetime_date.strftime('%B %d, %Y')
game_time = datetime_date.strftime('%-I:%M %p')
context = {
'games': games,
'game_date': game_date,
'game_time': game_time
}
return render(request, 'games/games.html', context)
{% for game in games %}
<div class="col-12 col-lg-6 mb-4">
<div class="gamecard p-2">
<div class="row">
<div class="col-12">
<h3 class="game-summary white opacity-90 text-center font-800 mb-
0">{{ game.summary }}
</h3>
<p class="white opacity-90 mb-0 text-center">
{{ game_date }}
{{ game_time }}
</p>
<p class="white opacity-90 mb-2 text-center"><small>
{{ game.venue.name }} - {{ game.venue.city }},
{{ game.venue.state }}</small>
</p>
</div>
</div>
{% endfor %}
问题是在你的循环中,在视图中:
for game in games:
date = game['schedule']['date']
datetime_date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ')
game_date = datetime_date.strftime('%B %d, %Y')
game_time = datetime_date.strftime('%-I:%M %p')
您不断地覆盖变量的值game_date
and game_time
), (还有date
and datetime_date
,但这些并不重要,因为它们只是您不在循环外使用的临时值),等等。所以不可避免地,当你稍后访问它时——在模板中,正如它发生的那样——它具有从games
数组的最后一个元素计算的值。
从您的模板中,您显然不希望这些是单个变量,每个变量都保存一个值 - 您希望它们存在,具有不同的值,用于列表的每个元素。由于game
无论如何每个显然都是一个字典,因此最简单的方法是简单地将数据添加到具有您需要的属性的那些字典中。
for game in games:
date = game['schedule']['date']
datetime_date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%fZ')
game['game_date'] = datetime_date.strftime('%B %d, %Y')
game['game_time'] = datetime_date.strftime('%-I:%M %p')
然后在模板中,而不是
{{ game_date }}
{{ game_time }}
像这样使用它:
{{ game.game_date }}
{{ game.game_time }}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句