2011-08-12 37 views
4

我在我的網站上使用圖片庫應用程序。目前,我將圖像文件放在目錄中,並手動爲每個圖像編寫img html標籤。是否有可能使django自動在目錄中創建一個文件列表,並將json輸出發送到圖庫應用程序,以便我可以使javascript爲每個圖像文件生成<img>元素。或者,無論何時請求Gallery應用,我可以直接讓django爲目錄中的每個文件自動生成<img>元素。Django:自動生成目錄中的文件列表

+1

是的,你可以。 Django是一個Python,因此您可以使用Python算法在目錄中創建文件列表,然後使用它來生成元素或使用'for'模板標記來執行此操作。 – Dracontis

回答

14

這裏的一些代碼對你:

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 %} 
3
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-annoying包;)