4

I need to generate unique id in each loop instead of ````city-selected```

{% for form in formset.forms %}
    <tr>
        {% for field in form %}
            <td class="input_td{% if field.errors %} error_td{% endif %}">
                <select name="city-select" id="city-select"></select>
            </td>
        {% endfor %}
        <td class="delete_formset_td"></td>
    </tr>
{% endfor %}

How can I generate it here?

I need some thing like this for ids:

output:

city-1
city-2
city-3
...
MHB
  • 625
  • 2
  • 10
  • 20
  • Does this answer your question? [How to generate random numbers in django](https://stackoverflow.com/questions/6353558/how-to-generate-random-numbers-in-django) – Anurag Srivastava Mar 09 '20 at 15:29
  • no, first I need it in django-template in the front-end. second I need something like ````city-select-i```` but I don't know how should I generate that ID and use it in ````name```` and ````id```` sections. @AnuragSrivastava – MHB Mar 09 '20 at 15:32
  • Does this answer your question? [Django template counter in nested loops](https://stackoverflow.com/questions/13870890/django-template-counter-in-nested-loops) Take a look at the second answer. – Ivan Starostin Mar 09 '20 at 15:33
  • How can I use that generated text in id section? @IvanStarostin – MHB Mar 09 '20 at 15:35
  • 1
    `id="city-select-{{ variable }}"` – Ivan Starostin Mar 09 '20 at 15:42
  • it worked. thanks @IvanStarostin – MHB Mar 09 '20 at 15:51

1 Answers1

7

You can use {{ forloop.counter }}. It gives you the loop iteration as a number.

See here.

{% for field in form %}

    <!-- your html -->

    city-{{ forloop.counter }}

{% endfor %}
GTBebbo
  • 1,198
  • 1
  • 8
  • 17