[Answer]-Check if item is in date, else print default

1👍

You can solve the problem with a template filter:

  1. Create a file for the filters (i.e. <YOUR_APP>/templatetags/<YOUR_FILTERS>.py) and add following code:

    from django.template import Library
    from django.utils.datetime_safe import datetime
    
    register = Library()
    
    @register.filter
    def full_month_price_list(value):
        month_list = [[datetime(2013, i, 1)] for i in xrange(1, 13)]
        for item in value:
            month_list[item.date.month - 1].append(item)
        return month_list
    

    This filter takes the list of items with a date attribute and returns a list with 12 lists of 2 elements: the date and the item

  2. In your template code load the filters ({% load <YOUR_FILTERS> %}) and change this:

    <ul>
        {% for item in product.list|dictsort:"date" %}
            <li>{{ item.price }} - {{ item.date|date }}</li>
        {% endfor %}
    </ul>
    

    by (UPDATED to format as table as you request in comments):

    <table>
        {% for item in product.list|full_month_price_list %}
        <tr>
            <td>{{ item.0|date:"b. j, Y" }}</td>
            <td>{{ item.1.price|default:"MISSING VALUE" }}</td>
        </tr>
        {% endfor %}
    </table>
    

    Note that you access to any property of the product item.1.date, item.1.price, item.1.pk, etc.

Replacing <YOUR_APP> by the name of your django app, <YOUR_FILTERS> by the name you want to use for your filters file.

Note that a file named __init__.py is needed in the directory <YOUR_APP>/templatetags/.

More about custom filters in django docs.

Leave a comment