[Answered ]-Dynamically iterate over variables if it contains a url using Jinja

1๐Ÿ‘

โœ…

I solved the issue by passing all the photos as a list in the context dictionary, now views.py looks like

def listing(request, listing_id):
    listing = get_object_or_404(Listing, pk=listing_id)
    context = {
        'listing': listing,
        'photos': [listing.photo_1,listing.photo_2,listing.photo_3,listing.photo_4,listing.photo_5,listing.photo_6]
    }
    return render(request, 'listings/listing.html', context)

and my html code looks like

    {% for photo in photos %}
      {% if photo %}
        <div class="col-md-2">
          <a href="{{ photo.url }}" data-lightbox="home-images">
            <img src="{{ photo.url }}" alt="" class="img-fluid">
          </a>
        </div>
      {% endif %}
    {% endfor %}

it works pefectly. Thank you.

๐Ÿ‘คPranta Palit

Leave a comment