如何在Python中遍历列表

时间:2019-07-18 15:02:23

标签: python django

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

views.py

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

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

template.html

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

2 个答案:

答案 0 :(得分:2)

您可以构建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的Form 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 %}

答案 1 :(得分:1)

您总是在每次迭代中都覆盖时间。尝试类似

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

context = { 'time': time }
return render(request, 'website', context)
相关问题