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

标签 python html django django-forms django-templates

我使用复选框输入在页面上显示了 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>

当我点击recipes_list 中每个条目的标签时,它显然总是打开第一篇文章。在过去的几天里,我一直在寻找解决方案,了解如何在 html 中为每个模型条目提供唯一的 id,但我找不到适合这种情况的任何方法。我试过表单、模型表单、各种 javascript 和 php。我该怎么做?

最佳答案

您可以使用 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>

希望这对您有所帮助!

关于python - 使用 Django 的每个模型的唯一 HTML 元素 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16926707/

相关文章:

python - 如何将图像文件保存在 Postgres 数据库中?

html - 悬停框位置问题

javascript - 为什么输入类型 ='file' 不调度事件?

jquery - 我可以设置文件下载到的文件名吗?

python - View 采用 1 个位置参数,但给出了 2 个

python - 如何在 matplotlib 中反射(reflect)矩阵?

python - 如何编写 GRPC python 单元测试

python - 如何在Python迷宫游戏中分解一个函数来引用不同的 "levels"?

html - 缩小窗口时顶部栏不重新调用(HTML,CSS)

django - 如何使用直通表并指向 self 使用 ManyToManyField 设置 related_name