4👍
✅
Following Jeb’s suggeston in a comment, I created a custom template tag.
I replaced {{ forloop.counter }}
with {% counter %}
, a tag that simply prints how many times it’s been called.
Here’s the code for my counter tag.
class CounterNode(template.Node):
def __init__(self):
self.count = 0
def render(self, context):
self.count += 1
return self.count
@register.tag
def counter(parser, token):
return CounterNode()
1👍
This isn’t exactly neat, but may be appropriate for someone:
{% for article in articles %}
{% ifchanged article.section %}
{% if not forloop.first %}</ul>{% endif %}
<h4>{{article.section}}</h4>
<ul>
{% endifchanged %}
<li>{{forloop.counter}}. {{ article.headline }}</li>
{% if forloop.last %}</ul>{% endif %}
{% endfor %}
👤Tom
- [Django]-Facet multiple fields on search query set
- [Django]-Django Admin validation
- [Django]-Django REST Framework — is multiple nested serialization possible?
-1👍
I think you can use forloop.parentloop.counter inside of the inner loop to achieve the numbering you’re after.
👤Jeb
- [Django]-Django collectstatic result in S3ResponseError: 301 Moved Permanently
- [Django]-Django Advanced Filter not working in django-material admin Theme
- [Django]-Django Restful Framework model serializers get_validation_exclusions
- [Django]-Can the 'webagg' backend for matplotlib work with my django site?
- [Django]-How to reference generated permissions in Django 1.7 migrations
-1👍
You could just use an ordered list instead of unordered:
{% regroup articles by section as articles_by_section %}
<ol>
{% for article in articles_by_section %}
<h4>{{ article.grouper }}</h4>
{% for item in article.list %}
<li>{{ item.headline }}</li>
{% endfor %}
{% endfor %}
</ol>
Source:stackexchange.com