Lucas03
Lucas03

Reputation: 2347

django template print only first unique occurance

I have a pretty simple task to do but I do not know how to do it most effectively in django templates. Basically, this is what I am trying to accomplish:

Jan. 27, 2015
    first post
    second post
    third post
Jan. 28, 2015
    another post
    and other
    etc
Feb. 18, 2015
    again
    and again

This could be its model:

class Post(models.Model):
    date=models.DateField()
    name=models.CharField()

In views.py passing just queryset as posts:

Post.objects.filter(date__gte = date.today()).order_by("date")

And then in template priting it out with for cycle:

{% for post in posts%}
    {{post.name}}
{% endfor %}

How do I get printed unique date only once? Is it possible to do this in templates or do I have to take care of it in views? I found similar two year old post.

Upvotes: 1

Views: 167

Answers (2)

catavaran
catavaran

Reputation: 45575

You can use {% ifchanged %} template tag:

{% for post in posts %}
    {% ifchanged %}<h3>{{ post.date }}</h3>{% endifchanged %}
    <div>{{ post.name }}</div>
{% endfor %}

Upvotes: 0

user764357
user764357

Reputation:

There is an inbuilt template tag for that - regroup!

This isn't perfect, but with the documentation it should get you close.

{% regroup posts by date as date_list %}

<ul>
{% for date in date_list %}
    <li>{{ date.grouper }}
    <ul>
        {% for item in date.list %}
          <li>{{ date.name }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

Upvotes: 2

Related Questions