[Django]-Unique HTML element IDs for each model with Django

3๐Ÿ‘

โœ…

You can write a filter which gets the model name

from django import template
register = template.Library()

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

and in the template:

and in the template, wherever you want the 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

If you want to return the 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

and in the template:

{{obj.class_name}}
๐Ÿ‘คkarthikr

5๐Ÿ‘

You can use the forloop.counter to achieve this:

{% 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>

Hope this helps!

๐Ÿ‘คPaulo Bu

3๐Ÿ‘

Its simple use object primary key as id because its unique (unless you have another loop from another model):

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

Or use forloop.counter:

{% for r in recipes_list %}
    <input id="ac-{{ forloop.counter }}" type="checkbox" />
{% endfor %}
๐Ÿ‘คAamir Rind

Leave a comment