List products by category in Django template

django, django-templates

Solution

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 %}

Problem

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...

Original source