[Django]-Printing a list in a django template without a trailing comma

3👍

You can use the join template built-in (ref https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#join)

So your example:

<li>Producer:
  {% for producer in producers %}
    {% if not forloop.last %}
      {{ producer }},
    {% else %}
      {{ producer }}
    {% endif %}
  {% endfor %}
</li>

would simply become:

<li>Producer:
  {{ producers|join:', ' }}
</li>

0👍

You can send it as common separated string. Also it should be producers instead of producer

context = {'song': song, 'date_added': date_added, 'artist': artist, 
    'url': url, 'year': year, 'genres': genres, 'country': country,
    'producers': ','.join(map(str, song.producer.all())), 'label': label, 'source': source,
    'source_url': source_url, 'comments': comments}

Leave a comment