How to iterate through images in a folder from html file with django
These are the images I want to access where the numbers of folder's names are ids
📂 img
📂 1
📄 image1.png
📄 image2.png
📂 2
📄 image2.png
📄 image4.png
In views.py I send the img path to the html with this code
images_path = os.path.join(STATIC_URL, 'webapp', 'img')
# code
return render(request, 'webapp/index.html', {
'services': services,
'images_path': images_path
})
Then in index.html I have this
# code
{% for service in services %}
# code
<div id="imagesCarousel" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
# here I want to access to every image and show it in the carousel
</div>
</div>
{% endfor %}
Basically I want to do something like
{% for image in os.listdir(os.path.join(images_path, service.id)) %}
How can I achieve that?
I tried the above code but obviously it doesn't worked
One possible solution is to get the image paths for each service on the backend and add it to the context somehow.
For example, in views.py:
images_path = os.path.join(STATIC_URL, 'webapp', 'img')
# ... get services from somewhere
# add the image_paths as an attribute to each service
for service in services:
image_paths = os.listdir(os.path.join(images_path, service.id))
setattr(service, 'image_paths', image_paths)
return render(request, 'webapp/index.html', {
'services': services,
})
Then in index.html:
# code
{% for service in services %}
# code
<div id="imagesCarousel" class="carousel slide" data-bs-ride="carousel">
<div class="carousel-inner">
{% for image_path in image_paths %}
<!-- whatever goes here, e.g. <img src="{{image_path}}"> -->
{% endfor %}
</div>
</div>
{% endfor %}