views:

168

answers:

3

What's the best way to generate HTML which has a heading for each Category, and Products under that category in a Django template?

I toyed with the idea of having a passing a dictionary, or an ordered list...

A: 

used a sorted list in the view code,

sorted(dom_obj.objects.all(), key=lambda d: d.sort_key)

and then used the filter tag

{% ifchanged %}<h1>{{ prod.cat }}</h1>{% endifchanged %}
geejay
+2  A: 

Take a look at the regroup template filter

http://docs.djangoproject.com/en/dev/ref/templates/builtins/#regroup

With it you could do something like this:

{% regroup products by category as products_by_category %}
{% for c in products_by_category %}
  <h1>{{c.grouper}}</h1>
  <ul>
    {% for p in c.list %}
      <li>{{p.name}}</li>
    {% endfor %}
  </ul>
{% endfor %}
Wade
A: 

In addition to what @Wade suggests you can also add a method to your Category model to return the products it has.

Example..

class Category:
... 
...  
    def get_products(self):
        return Product.objects.filter(category=self)

Then in a template you can..

{% for category in categories %} # assuming categories is passed from the view.
    {% for product in category.get_products %}
...
utku_karatas