Leaozinho
Leaozinho

Reputation: 131

Printing a list in a django template without a trailing comma

My Django template was printing a list with the elements separated by comma, but the last item always had a comma as well. I was able to solve the problem in the template by doing the following:

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

But after reading some posts on here, I think it would be better to do it in the views.py file. I don't know how to do that and couldn't really understand the other posts on here. Here is the corresponding views file:

def song(request, song_id):
    """Show a single song."""
    song = Song.objects.get(id=song_id)
    date_added = song.date_added
    artist = song.artist
    url = song.url
    year = song.year
    genres = song.genre.all()
    country = song.country
    producer = song.producer.all()
    label = song.label
    source = song.source
    source_url = song.source_url
    comments = song.comments
    context = {'song': song, 'date_added': date_added, 'artist': artist, 
        'url': url, 'year': year, 'genres': genres, 'country': country,
        'producers': producer, 'label': label, 'source': source,
        'source_url': source_url, 'comments': comments}

    return render(request, 'great_songs_app/song.html', context)

Is there a way to turn 'producer' into a dictionary and pass it to the template in a way that all the items except for the last will be separated by a comma?

Upvotes: 3

Views: 530

Answers (2)

MichielB
MichielB

Reputation: 4285

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>

Upvotes: 3

SHIVAM JINDAL
SHIVAM JINDAL

Reputation: 2974

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}

Upvotes: 0

Related Questions