I have this code
{% for account in object_list %} <tr> {% for field, value in book.get_fields %} <th>{{ field.verbose_name }}</th> {% endfor %} </tr> {{ break }} {% endfor %}
I want to break the for loop after first iteration. break is not working
There is no break in Django template system but you can achieve an statement like break with bellow architecture. (Loop will go iteration but u don't do anything.) 1- Use with to define a variable to determine current status, 2- Use a template custom tag to change statement to negate current status.
But Django brings in the box an automatically creates a variable called forloop. counter that holds the current iteration index. {% for variable in variables %} {{ forloop.counter }} : {{ variable.variable_name }} {% endfor %} The forloop.
We can set the value of a variable in the Django template using with tag. This will output the below content. One downside of this approach is that we have to write the lines where we are accessing the variable inside with and endwith block. Using with is useful when using a costly variable multiple times.
I think you should use slice to achieve your goal
{% for account in object_list|slice:":1" %}
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