Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Auto-generating a list of files in a directory

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.

like image 793
nixnotwin Avatar asked Aug 12 '11 15:08

nixnotwin


2 Answers

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 %}
like image 60
Hoff Avatar answered Oct 13 '22 00:10

Hoff


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 ;)

like image 36
surfeurX Avatar answered Oct 13 '22 01:10

surfeurX