I use an image gallery app on my website. At present I drop image files in a directory, and write img html tags for each image manually. Is it possible to make django create a list of files in the directory automatically, and send the json output to the gallery app, so that I can make javascript to generate <img>
elements for each image files. Or, whenever gallery app is requested, can I directly make django to auto-generate <img>
elements for each of the files in a directory.
here's a bit of 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 %}
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}
this functions return a json object containing all images in a directory inside MEDIA_ROOT.
require the django-annoying packages ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With