[Django]-How to add commas / delimiters for all list items except last?

7👍

I agree join is a good approach. If you want to do it with for, try

{% for u in users %}
{{u.name}}{% if not forloop.last %},{% endif %}
{% endfor }

2👍

The for loop in Django 1.2 includes a few automatically generated variables. Among those are:

forloop.first
forloop.last

So you could place the delimiter using an if statement:

<p>
{% for u in users %}
{{u.name}}
{% if not forloop.last %}
,
{% endif %}
{% endfor %}
</p>

-1👍

If you don’t need to loop, and you just have a list, then ‘join’ is probably your best solution.

But first we need to get a list of all names, map should help us with that, then join all the results:

{% with names = map(lambda u: u.name, users) %}
{{ names|join:", " }}
{% endwith %}

Leave a comment