9

I am trying to get all image link present in a folder. Currently, I am assigning the link manually. But, I want my django to get all images from a specific folder irrespective of their names.

<li>
   <a href="{% static "styles/jamia/1.jpg" %}"  rel="prettyPhoto[gallery1]"><img src="{% static "styles/jamia/1.jpg" %}"></a>
</li> 

<li>
  <a href="{% static "styles/jamia/2.jpg" %}"  rel="prettyPhoto[gallery1]"><img src="{% static "styles/jamia/2.jpg" %}"></a>
</li>

I am looking for something like:

{% for file in {% static "styles/jamia/" %}  %}
    <img src="{{file}}" alt="">
{% endfor %}

All images are present in jamia folder.

learner
  • 4,614
  • 7
  • 54
  • 98

2 Answers2

9

This isn't something Django has built in. But Django is just Python, and you can use normal Python file functions to get your list in the view:

files = os.listdir(os.path.join(settings.STATIC_ROOT, "styles/jamia"))
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 2
    Now, I can iterate through `files`. How should I use it? In views or in template? – learner May 17 '16 at 08:26
  • 1
    @learner, I have the same issue just like yours, and I think what Daniel meant is that we need to iterate the files in Python views, and pass them as context objects to templates, and then in templates we could `for-loop` to create the html elements. But that's not the solution I'm looking for, maybe I'll try js directly in templates. – avocado Feb 02 '20 at 12:30
2

This seems to have been answered in parts before, but probably requires some searching for all the answers. So in an attempt to provide a complete answer to this questions in one place:

In views.py you would want to do something like the other answer says:

context_dict = {}
files = os.listdir(os.path.join(settings.STATIC_DIR, "styles/jamia/"))
context_dict['files'] = files
return render(request, 'home.html', context=context_dict)

Then in your html template you can loop over your images. In addition, we make use of with to join the root to the static file with those names pulled out in the views.py, but you could have concatenated the whole path in views and not needed with. So, in home.html:

{% for file in files %}
    {% with 'images/'|file as image_static %}
        <img src="{% static image_static %}" alt="">
    {% endwith %}
{% endfor %}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Josh Mitton
  • 141
  • 1
  • 3