Django manytomany in template format

ApPeL picture ApPeL · Feb 7, 2011 · Viewed 9k times · Source

In one of my models I have a categories field that is a manytomany configuration.

I was wondering how to get the following output in the template.

Category 1, Category 2, Category 3 and Category 4

So basically separate each category with a comma, apart from the last one that then gets replaced with a "and"

Answer

Daniel Roseman picture Daniel Roseman · Feb 7, 2011
{% for category in myob.categories.all %}
  {{ category }}
  {% if not forloop.last %},{% else %} and {% endif %}
{% endfor %}