'Using Django cycle template tag to number rows
I am trying to use Django cycle to make my css class have the current table row number in it. I'm trying the following:
{{ formset.management_form }}
{% for form in formset %}
<tr class="{% cycle 'row1' 'row2' 'row3' %} formset_row">
{% for field in form.visible_fields %}
<td>
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
Where my rows are added dynamically using jquery.formset.js https://gist.github.com/vandorjw/f884f0d51db3e7caaecd
For some reason this just gives me
<tr class="row1 formset_row">...</tr>
<tr class="row1 formset_row">...</tr>
<tr class="row1 formset_row">...</tr>
<tr class="row1 formset_row">...</tr>
...
Why isn't this working?
From what I understand this will give me
row1 row2 row3 row1 row2 row3 row1...
How can I make this continue counting...
row1 row2 row3 row4 row5 row6 row7...
Solution 1:[1]
I'm not sure why it's not working, but if you want it to continue counting along with the entire loop, you can use
class="row{{forloop.counter}}"
Solution 2:[2]
**In short way **
#Create template_tag.py file in your root file
from django import template
register = template.Library()
@register.filter
def modulo(num, val):
return num % val
``
*then in your html template load {% load template_tags %}*
call it into your table row
<td>{{forloop.counter}}</td>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | user18220914 |
