Как перебирать изображения в папке из html-файла с помощью django

Вот изображения, к которым я хочу получить доступ, где номера имен папок - это id

📂 img
  📂 1 
    📄 image1.png
    📄 image2.png
  📂 2
    📄 image2.png
    📄 image4.png

В views.py я отправляю путь к img в html с помощью этого кода

images_path = os.path.join(STATIC_URL, 'webapp', 'img')
# code
return render(request, 'webapp/index.html', {
        'services': services,
        'images_path': images_path
    })

Затем в index.html я имею следующее

# 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 %}

В основном я хочу сделать что-то вроде

{% for image in os.listdir(os.path.join(images_path, service.id)) %}

Как я могу этого достичь?

Я попробовал вышеприведенный код, но очевидно, что он не работает

Одним из возможных решений является получение путей изображений для каждого сервиса на бэкенде и добавление их в контекст каким-либо образом.

Например, в файле 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,
})

Затем в 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 %}
Вернуться на верх