Django: automatically create a list of files in a directory

I am using the image gallery application on my website. Currently I am throwing image files into a directory and writing img html tags for each image manually. Is it possible to create django a list of files in a directory automatically and send json output to the gallery application so that I can create javascript to create elements <img>for each image file. Or, when the gallery application is requested, can I make django to automatically create items <img>for each of the files in the directory.

+5
source share
2 answers

here is some code for you:

views.py

import os 

def gallery(request):
    path="C:\\somedirectory"  # insert the path to your directory   
    img_list =os.listdir(path)   
    return render_to_response('gallery.html', {'images': img_list})

gallery.html

{% for image in images %}
<img src='/static/{{image}}' />
{% endfor %}
+15
import os
from django.conf import settings
from annoying.decorators import ajax_request

@ajax_request
def json_images(request, dir_name):
    path = os.path.join(settings.MEDIA_ROOT, dir_name)
    images = []
    for f in os.listdir(path):
        if f.endswith("jpg") or f.endswith("png"): # to avoid other files
            images.append("%s%s/%s" % (settings.MEDIA_URL, dir_name, f)) # modify the concatenation to fit your neet
    return {'images': images}

json, MEDIA_ROOT.

django- ;)

+3

All Articles