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

时间:2013-06-04 20:18:26

标签: 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。我怎么能这样做?

3 个答案:

答案 0 :(得分: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>

希望这有帮助!

答案 1 :(得分:3)

它简单地使用对象主键作为id,因为它是唯一的(除非你有另一个模型的另一个循环):

{% for r in recipes_list %}
    <input id="ac-{{ r.id }}" type="checkbox" />
{% endfor %}

或使用forloop.counter

{% for r in recipes_list %}
    <input id="ac-{{ forloop.counter }}" type="checkbox" />
{% endfor %}

答案 2 :(得分:2)

您可以编写一个获取型号名称的过滤器

from django import template
register = template.Library()

@register.filter(name='class_name')
def class_name(obj):
  return obj.__class__.__name__

并在模板中:

并在模板中,无论您想要id / classname:

<article id={{obj|class_name}}>
  {# further code #}
</article>

OR

class MyModel(models.Model):
    #fields

    def class_name(self):
        return "%s"%self.__class__.__name__ #returns the model instance name

如果要返回实例名称:

from django.template.defaultfilters import slugify
class MyModel(models.Model):
    def class_name(self):
        return "%s"%(slugify(self.name)) #or whatever field has the specific instance name

并在模板中:

{{obj.class_name}}
相关问题