Search code examples
pythondjangofor-looplettucetemplatetag

Is there a pythonic way of knowing when the first and last loop in a for is being passed through?


I have a template in which I placed, let's say 5 forms, but all disabled to be posted except for the first one. The next form can only be filled if I click a button that enables it first.

I'm looking for a way to implement a Django-like forloop.last templatetag variable in a for loop inside an acceptance test to decide whether to execute a method that enables the next form or not.

Basically what I need to do is something like:

for form_data in step.hashes:
    # get and fill the current form with data in form_data
    if not forloop.last:
        # click the button that enables the next form
# submit all filled forms

Solution

  • If I am understanding your question correctly, you want a simple test for whether you are at the beginning or end of the list?

    If that's the case, this would do it:

    for item in list:
        if item != list[-1]:
            #Do stuff
    

    For the first item in the list, you would replace "-1" with 0.