如何在Python中迭代列表

2024-04-25 21:17:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的for循环来迭代各种日期的列表。对于列表中的每个项目,我只使用前10个字符来排除时区。但是,当我将对象传递给模板时,所有值只返回列表中的第一个值。你知道吗

你知道吗视图.py你知道吗

for opportunity in opportunities:
    temp = opportunity['expectedCloseDate']
    time = temp[:10]

context { 'time': time }
return render(request, 'website', context)

你知道吗模板.html你知道吗

<div class="control is-inline-flex">
    <input class="input" name="close_date" id="close_date" type="date" value="{{ time }}" disabled>
</div>

Tags: 项目对象div模板列表forcloseinput
2条回答

每次迭代都会覆盖时间。试试这样的

time = []
for opportunity in opportunities:
    temp = opportunity['expectedCloseDate']
    time.append(temp[:10])

context = { 'time': time }
return render(request, 'website', context)

您可以构建times列表:

times = [opportunity['expectedCloseDate'][:10] for opportunity in opportunities]
return render(request, 'website', {'times': times})

然后在模板中迭代:

<div class="control is-inline-flex">
    {% for time in times %}
        <input class="input" name="close_date" id="close_date" type="date" value="{{ time }}" disabled>
    {% endfor %}
</div>

也就是说,看起来您正在手动构建表单。在这里使用Django的^{} object [Django-doc]通常更好。你知道吗

如果要在两个列表上同时循环,可以使用zip,如:

times = [opportunity['expectedCloseDate'][:10] for opportunity in opportunities]
opps_times = zip(opportunities, times)
return render(request, 'website', {'opps_times': opps_times})

并将其渲染为:

{% for opportunity, time in opps_times %}
    <!  ...  >
{% endfor %}

相关问题 更多 >