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
Unlike other languages, Python does not use an end statement for its loop syntax. The initial Loop statement is followed by a colon : symbol. Then the next line will be indented by 4 spaces. It is these spaces to the left of the line that is key.
We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list. The output would be the same as above.
To detect the last item in a list using a for loop: Use the enumerate function to get tuples of the index and the item. Use a for loop to iterate over the enumerate object. If the current index is equal to the list's length minus 1 , then it's the last item in the list.
Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.
I don't know of anything built-in, but you can easily write a generator to give you the required information:
def firstlast(seq):
seq = iter(seq)
el = prev = next(seq)
is_first = True
for el in seq:
yield prev, is_first, False
is_first = False
prev = el
yield el, is_first, True
>>> list(firstlast(range(4)))
[(0, True, False), (1, False, False), (2, False, False), (3, False, True)]
>>> list(firstlast(range(0)))
[]
>>> list(firstlast(range(1)))
[(0, True, True)]
>>> list(firstlast(range(2)))
[(0, True, False), (1, False, True)]
>>> for count, is_first, is_last in firstlast(range(3)):
print(count, "first!" if is_first else "", "last!" if is_last else "")
0 first!
1
2 last!
You could use enumerate
and compare the counter with the length of the list:
for i, form_data in enumerate(step.hashes):
if i < len(step.hashes):
whatever()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With