Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django loop – remove last comma

Tags:

django

I have the following loop set up, but need to remove the comma on the last item (it's to replicate a JSON array for cycle2)

{% for product_in_series in series.get_products %}{%spaceless%}
    {% with product_in_series.product as product %}
    {%if not forloop.first%}
            "<img src='{% version product.get_overview 'page_image' %}'>",
    {%endif%}
    {% endwith %}
{%endspaceless%}{% endfor %}

Cheers, R

like image 225
John the Painter Avatar asked Mar 22 '14 16:03

John the Painter


People also ask

How do you end a comma in python?

Python 3 changes this completely and the trailing comma is no longer accepted. You use the end parameter to change the line ending, setting it to a blank string to get the same effect. More like a necessary consequence.


Video Answer


3 Answers

What about this?

{% for product_in_series in series.get_products %}{%spaceless%}
    {% with product_in_series.product as product %}
    {%if not forloop.first%}
        "<img src='{% version product.get_overview 'page_image' %}'>"
        {%if not forloop.last%},{%endif%}
    {%endif%}
    {% endwith %}
{%endspaceless%}{% endfor %}
like image 74
Selcuk Avatar answered Oct 23 '22 16:10

Selcuk


{{ forloop.last|yesno:",&#44;"|safe }}

&#44; - is a comma

like image 42
Unicorn Avatar answered Oct 23 '22 17:10

Unicorn


None of the above works for me. The correct syntax, as in Django 3.0, is as such

 {% with querythisandthat as A %}
   {% for  u in A %}  {{ u.interesting_stuff }} 
      {% if u == A.last %} . {% else %} ; {% endif %}
   {% endfor %}
 {% endwith %}

The reason is that A.last is not True/False, but it is the last element of the queryset

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.first

like image 35
am70 Avatar answered Oct 23 '22 15:10

am70