views:

42

answers:

3

Hay, i have a field in one of my models which saves the creation date of an object

created_on = models.DateTimeField(blank=False, auto_now_add=True)

This works as expected.

In my templates i want to list objects like this

June 15
{{ objects here which was created on June 15 }}
June 14 
{{ objects here which was created on June 14 }}

etc

Any idea how i would go about doing this?

Thanks in advance.

A: 

Hi, you can for example generate list of dates(by day on given interval) in your view ordered from min to max, and get all objects in this interval. Then create templatetag that takes 2 arguments queryset and date, and filter records which created(or something else) by your date.

Saff
+1  A: 

The place for this is in the template, not the view.

You want the ifchanged template filter, which you use like this:

<h1>Archive for {{ year }}</h1>

{% for entry in entries %}
    {% ifchanged %}<h3>{{ entry.date|date:"F" }}</h3>{% endifchanged %}
    <p>{{ entry.date|date:"j" }} - {{ entry.title }}</p>
{% endfor %}

In this example, every time the month changes, a heading showing the month will be printed.

ifchanged can do some relatively complex things (e.g. checking if multiple variables have all changed), and can have an optional else block - see the docs for more.

Dominic Rodger
where does yearcome from? and would entry.date|date:"f" be entry.created_on|date:"f" ?
dotty
I've used this code and implement another ifchanged block {% ifchanged %}<h4>{{ listing.created_on|date:"d" }}</h4>{% endifchanged %} however, if a month only has 1 entry it in, it fails to render to day as a title
dotty
+2  A: 

First in the view, make sure your objects are ordered by the 'created_on' field.

object_list = MyObjs.objects.all().order_by('created_on')

I believe you should then be able to use the following code in your template:

{% regroup object_list by created_on|date:"Y-m-d" as objects_by_day %}

{% for day in objects_by_day %}
    {{day.list.0.created_on|date:"M d"}}
    {% for obj in day.list %}
        {{obj}}
    {% endfor %}
{% endfor %}

This makes use of the regroup template tag, grouping the items by day, creating a list of objects per day. The date itself is output by using the 'date' template filter to reformat the created_on field of the first item in that date's list.

[Note: I have not tested this!]

msanders
this solution works well. What does day.list.0.created_on|date:"M d" do?
dotty
'day.list' is a list of your objects all created on a particular day. 'day.list.0' is the first object in that list. 'day.list.0.created_on' is the creation date in datetime format. I am using the Django template date' filter to convert it to 'June 15' format - see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
msanders