[Fixed]-Show title only once inside django if statement

1๐Ÿ‘

โœ…

Iโ€™m not overly familiar with Django and Python anymore, but I guess you could do a preliminary check to see if there are damages with or without images in there.

damages_with_images = [d for d in damages if d.images.length > 0]
damages_without_images  = [d for d in damages if d.images.length == 0]

And then just loop over these two separate arrays, and only print the heading if they are not emptyโ€ฆ

{% if damages_with_images|length > 0 %}
  put heading1
{% endif %}
# ... loop ...

{% if damages_without_images|length > 0 %}
  put heading2
{% endif %}
# ... loop ...

Of course this has worse performance because of multiple loops.

0๐Ÿ‘

What I would do in your position is

  1. Either pass two separate QuerySets in the template, the first would include damages with images and the other damages without images.

  2. Leave the QuerySet as is and create two custom template filters that would do the same job as the step #1 above.

Case 1:

# views.py

def my_view(request):
    damages_w_img = Damage.objects.filter(images__isnull=False)
    damages_wo_img = Damage.objects.filter(images__isnull=True)
    return render(request, 'template.html', locals())


<!-- template.html -->

{% if damages_w_img.exists %}
    <h1>This list of damages contains images</h1>
    {% for damage in damages_w_img %}
        do stuff here, each damage has an image
    {% endfor %}
{% endif %}

{% if damages_wo_img.exists %}
    <h1>This list of damages does not contain images</h1>
    {% for damage in damages_wo_img %}
        do stuff here, each damage does not has an image
    {% endfor %}
{% endif %}

Case 2:

# custom_template_filter.py

from django import template

register = template.Library()

@register.filter
def with_images(damages):
    return damages.objects.filter(images__isnull=False)

@register.filter
def without_images(damages):
    return damages.objects.filter(images__isnull=True)


<!-- template.html -->

{% with damage_w_img=car.damages|with_images damage_wo_img=car.damages|without_images %}

    {% if damages_w_img.exists %}
        <h1>This list of damages contains images</h1>
        {% for damage in damages_w_img %}
            do stuff here, each damage has an image
        {% endfor %}
    {% endif %}

    {% if damages_wo_img.exists %}
        <h1>This list of damages does not contain images</h1>
        {% for damage in damages_wo_img %}
            do stuff here, each damage does not has an image
        {% endfor %}
    {% endif %}

{% endwith %}

Leave a comment