1

My html file generates a table:

{% for resp in results %}
    <tr style="counter-increment: count">
         <td>{{ resp }}</td>
         <td>{{ resp.Question_id.Statement }}</td>
    </tr>
{% endfor %}

How do I assign an id to the first td every time a new row is generated?

Lloyd
  • 161
  • 3
  • 11
  • What `id`? That of the `Question`? Or just the index of the `for` loop? Furthermore the syntax hints that you used `Question_id` as a `ForeignKey`, which is not really the way one is supposed to name a relation. – Willem Van Onsem Jul 26 '18 at 12:14
  • 2
    https://stackoverflow.com/questions/11481499/django-iterate-number-in-for-loop-of-a-template#11481619 – SuperShoot Jul 26 '18 at 12:17
  • Possible duplicate of [Django - iterate number in for loop of a template](https://stackoverflow.com/questions/11481499/django-iterate-number-in-for-loop-of-a-template) – Brown Bear Jul 26 '18 at 12:29
  • i want the first td to have an id so it would look like – Lloyd Jul 26 '18 at 12:52

2 Answers2

3

use the forloop.counter template var:

{% for resp in results %}
    <tr style="counter-increment: {{ forloop.counter }}">
         <td>{{ resp }}</td>
         <td>{{ resp.Question_id.Statement }}</td>
    </tr>
{% endfor %}
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
2

Use:

forloop.counter The current iteration of the loop (1-indexed)

More info at: https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#for

{% for item in item_list %}
    {{ forloop.counter }} {# starting index 1 #}
    {{ forloop.counter0 }} {# starting index 0 #}

    {# do your stuff #}
{% endfor %}
Adelina
  • 10,915
  • 1
  • 38
  • 46
  • It's probably better to refer to the current documentation https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for – T.Nel Jul 26 '18 at 12:17