[英]How to Iterate Over a List in Python
I have a simple for loop to iterate over a list of various dates. 我有一个简单的for循环,可以迭代各种日期的列表。 For each item in the list, I exclude the timezone by taking only the first 10 characters.
对于列表中的每个项目,我仅采用前10个字符来排除时区。 However, when I pass the object to my template only the first value in the list is being returned for all values.
但是,当我将对象传递给模板时,仅返回所有值的列表中的第一个值。
views.py views.py
for opportunity in opportunities:
temp = opportunity['expectedCloseDate']
time = temp[:10]
context { 'time': time }
return render(request, 'website', context)
template.html template.html
<div class="control is-inline-flex">
<input class="input" name="close_date" id="close_date" type="date" value="{{ time }}" disabled>
</div>
You can construct a list of times
: 你可以构造名单
times
:
times =
[opportunity['expectedCloseDate'][:10] for opportunity in opportunities
]
return render(request, 'website', {'times': times})
and then iterate over this in your template: 然后在您的模板中对此进行迭代:
<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>
That being said, it looks like you are building a form manually. 话虽如此,看起来您正在手动构建表单。 It is usually better to use Django's
Form
object [Django-doc] here. 通常最好在这里使用Django的
Form
对象[Django-doc] 。
If you want to loop concurrently over two lists, you can make use of zip
, like: 如果要同时在两个列表上循环,可以使用
zip
,例如:
times = [opportunity['expectedCloseDate'][:10] for opportunity in opportunities]
opps_times =
zip(opportunities, times
)
return render(request, 'website', {'opps_times':
opps_times})
and render this with: 并使用以下代码呈现:
{% for
opportunity, time in
opps_times %}
<!-- ... -->
{% endfor %}
You are always overwriting time in each iteration. 您总是在每次迭代中都覆盖时间。 Try something like
尝试类似
time = []
for opportunity in opportunities:
temp = opportunity['expectedCloseDate']
time.append(temp[:10])
context = { 'time': time }
return render(request, 'website', context)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.