forloop.counter

I need to have numbering for table so i am using forloop.counter but i have a problem. i am having a for loop with if condition where there is transaction id as follows:

{% for order in order_list %}
    {% if order.transaction_id %}
	<tr>
	<td>{{ forloop.counter }}</td>
	<td>{{order.id}}</td>
	<td>{{order.transaction_id}}</td>
	<td>{{order.customer}}</td>
	<td>{{order.date_ordered}}</td>
	<td><a href="{% url 'detailed-transactions' order.id %}">{{ order.transaction_id }}</a></td>
	</tr>
    {% endif %}
{% endfor %}

since i am checking for transaction id then some records will not be present but the loop will keep going so i will get numbers like 2,5,6 instead of records 1,2,3

first column from left is the numbers which should be 1,2 instaed of 2,5 but it is 2,5 because records 2,5 have the transaction id. I need to put in first column the number of records 1,2 instead of where the records are just like it says 2,5.

Thanks.

I found the solution with jscript

<script> var counter = 0 </script>
{% for order in order_list %}
	{% if order.transaction_id %}
	<tr>
	<td id="{{forloop.counter}}">{{ forloop.counter }}</td>
	<script>
		var counter = counter + 1
		var s{{forloop.counter}} = counter
		document.getElementById("{{forloop.counter}}").innerHTML = s{{forloop.counter}};
	</script>
	<td>{{order.id}}</td>
	<td>{{order.transaction_id}}</td>
	<td>{{order.customer}}</td>
	<td>{{order.date_ordered}}</td>
	<td><a href="{% url 'detailed-transactions' order.id %}">{{ order.transaction_id }}</a></td>
	</tr>
    {% endif %}
 {% endfor %}
1 Like

While this “works”, this really isn’t your best solution.

The better / more appropriate solution is to change your view such that only the elements of order_list that you want to render in your template are passed to the template in the context.

It’s a lot better to do your filtering in the view and not in the template.

2 Likes

Thank you for your advice