"Last" tag does not work

I have a set of "promotion" requests that appear in the template. Each of these promotions also has 1 or more purposes. I want to show the dates of the first and last appointments.

While using the "first" tag. However, using the "last" tag causes:

TemplateSyntaxError exception value: Caught an exception while rendering: Negative indexing is not supported.

Here is the script template

{% for promotion in promotions%}
    {% with promotion.appointment_set.all as appointments %}
        {% with appointments|first as first_ap %}
            {{ first_ap.date|date }}
        {% endwith %}

        {% with appointments|last as last_ap %}
            {{ last_ap.date|date }}
        {% endwith %}
    {% endwith %}
{% endfor %}

What am I doing wrong here?

+3
source share
3 answers

last , , , : collection[-1]. , , .

, - Promotion, :

class Promotion(models.Model):
    ... fields, etc ...

    def get_last_appointment(self):
        try:
            return self.appointment_set.all().order_by('-date')[0]
        except IndexError:
            pass

:

{{ promotion.get_last_appointment.date|date }}
+2

, , , :

return render_to_response(template, { 
     appointments: list(Appointments.objects.all()) 
})

, - ( ):

{% for ap in appointments %}
  {% ifequal ap appointments|last %}
    ap.date
  {% endifequal %}
{% endfor %}

. : ap.user.full_name

+5

, @Daniel : Querysets . .

Another way to solve this problem is to add a custom filter that will work with lists and queries. Sort of:

@register.filter
def custom_last(value):
    last = None

    try:
        last = value[-1]
    except AssertionError:
        try:
            last = value.reverse()[0]
        except IndexError:
            pass

    return last

And in the template:

{% with appointments|custom_last as last_ap %}
+3
source

Source: https://habr.com/ru/post/1764148/


All Articles