Iterate through a static image folder in django

后端 未结 2 1447
清歌不尽
清歌不尽 2021-01-12 12:24

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 irrespecti

相关标签:
2条回答
  • 2021-01-12 12:47

    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 %}
    
    0 讨论(0)
  • 2021-01-12 12:53

    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"))
    
    0 讨论(0)
提交回复
热议问题