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}}
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!
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 %}
- [Django]-Django can't process non-ascii symbols
- [Django]-Python Django โ Keep user log in session between views
- [Django]-Django invite code app recommendation?
Source:stackexchange.com