Django:自动生成目录中的文件列表

nix*_*win 8 python django image list

我在我的网站上使用图片库应用程序.目前我将图像文件放在目录中,并手动为每个图像编写img html标签.是否可以让django自动在目录中创建文件列表,并将json输出发送到gallery应用程序,这样我就可以使用javascript <img>为每个图像文件生成元素.或者,每当请求gallery应用程序时,我是否可以直接使django为<img>目录中的每个文件自动生成元素.

Hof*_*off 17

这里有一些代码给你:

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})
Run Code Online (Sandbox Code Playgroud)

gallery.html

{% for image in images %}
<img src='/static/{{image}}' />
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


sur*_*urX 5

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}
Run Code Online (Sandbox Code Playgroud)

此函数返回一个 json 对象,其中包含 MEDIA_ROOT 内目录中的所有图像。

需要 django-annoying 包;)