Reputation: 43
I am trying to display multiple images (20 - 30) with the image file also being displayed.
I have the images displayed but I am not sure how to get the image file name to display beside it / underneath it.
I am new to Django.
Here's what I have done so far:
template.html
<div class="container-fluid my-container">
{% filter_images_normal 6 as images %}
<div class="row no-pad display-flex my-row">
{% for image in images %}
<div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col- my-col my-col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4 my-col">
<input class="img-thumbnail" type="image" id="image" alt="Image" src="{{ MEDIA_URL}}{{ image }}">
<p>Image name file here</p>
</div>
{% endfor %}
</div>
</div>
filter_images.py (template tag)
@register.simple_tag
def filter_images_normal(count=3):
valid_extensions = ('.jpg', '.jpeg', '.png', '.gif')
rand_dir = '/static/app_filter/images/normal/'
path = '/app_filter/static/app_filter/images/normal/'
files = [f for f in os.listdir(settings.BASE_DIR + path)
if f[f.rfind("."):] in valid_extensions]
# print(random.sample(files, count))
print(rand_dir)
return [rand_dir + filename for filename in random.sample(files, count)]
Upvotes: 2
Views: 1661
Reputation: 21690
pass image as list of dict from template tag:
@register.simple_tag
def filter_images_normal(count=3):
valid_extensions = ('.jpg', '.jpeg', '.png', '.gif')
rand_dir = '/static/app_filter/images/normal/'
path = '/app_filter/static/app_filter/images/normal/'
files = [f for f in os.listdir(settings.BASE_DIR + path)
if f[f.rfind("."):] in valid_extensions]
# print(random.sample(files, count))
print(rand_dir)
return [{'name':filename, 'url':rand_dir + filename} for filename in random.sample(files, count)]
in template call {{image.url}}
and {{image.name}}
<div class="row no-pad display-flex my-row">
{% for image in images %}
<div class="col-xl-4 col-lg-4 col-md-4 col-sm-4 col- my-col my-col-xl-4 col-lg-4 col-md-4 col-sm-4 col-4 my-col">
<input class="img-thumbnail" type="image" id="image" alt="Image" src="{{ MEDIA_URL}}{{image.url}}">
<p>{{ image.name }}</p>
</div>
{% endfor %}
</div>
Upvotes: 1