How to Iterate Over a List in Python

I have a simple for loop to iterate over a list of various dates. For each item in the list, I exclude the timezone by taking only the first 10 characters. However, when I pass the object to my template only the first value in the list is being returned for all values.

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 answers

  • answered 2019-07-18 15:07 mark

    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)
    

  • answered 2019-07-18 15:08 Willem Van Onsem

    You can construct a list of 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.

    If you want to loop concurrently over two lists, you can make use of zip, like:

    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 %}