使用Django的每个模型的唯一HTML元素ID

Ben*_*Ben 2 html python django django-templates django-forms

我有django模型在页面上显示使用复选框输入,其上面有一个标签,如下所示:

{% if recipes_list %}
<table>
{% for r in recipes_list %}
<tr>
  <td>
    <section class="ac-container">
      <div>
        <input id="ac-1" type="checkbox" />
        <label for="ac-1">{{r.name}}</label>
        <article class="ac-small">
        <ul>
        {% for i in r.ingredient_list%}
          <li>{{i.part}}, {{i.amount}}</li>
        {% endfor %}
        </ul>
        </article>
      </div>
    </section>
 </td>
</tr>
{% endfor %}
</table>
Run Code Online (Sandbox Code Playgroud)

当我点击每个条目的标签时recipes_list,它显然总是打开第一个条目的文章.我一直在寻找过去几天关于如何在html中为每个模型条目提供唯一ID的解决方案,但我找不到任何适用于这种情况的东西.我尝试过表单,模型表单,各种javascript和php.我怎样才能做到这一点?

Pau*_* Bu 5

您可以使用forloop.counter来实现此目的:

{% if recipes_list %}
<table>
{% for r in recipes_list %}
<tr>
  <td>
    <section class="ac-container">
      <div>
        <input id="ac-{{forloop.counter}}" type="checkbox" />
        <label for="ac-{{forloop.counter}}">{{r.name}}</label>
        <article id="article-{{forloop.counter}}" class="ac-small">
        <ul>
        {% for i in r.ingredient_list%}
          <li>{{i.part}}, {{i.amount}}</li>
        {% endfor %}
        </ul>
        </article>
      </div>
    </section>
 </td>
</tr>
{% endfor %}
</table>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!