我剛剛學習Python & Django。 (感謝大家誰在這裏貢獻 - 這是一個寶貴的資源!)在Django模板中列出目錄文件內容
我遇到的一個看似基本的事情是呈現一個簡單的靜態文件列表(比如我的單個存儲庫目錄的內容服務器)作爲可下載鏈接的列表。這是否是安全的,那是另一問題,但假設我要做到這一點...
這篇文章幫助引導我朝着正確的方向: Python directory list returned to Django template
這段代碼輸出文件名中的「myfiles的」如果從提示符下運行:
path= os.path.dirname(os.path.abspath(__file__))
myfiles = os.path.join(path, 'myfiles')
os.chdir(myfiles)
for files in os.listdir("."):
print files
但我怎麼這些文件傳遞到Django模板並生成鏈接列表?我想我可能需要創建一個Python字典/元組來使其具有可迭代性,將它作爲模板變量傳遞並將其呈現在for循環中?
是否必須向我的urls.py文件添加條目才能使其工作?像這樣?
(r'^myfiles/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'myfiles'), 'show_indexes': True}),
感謝您的幫助!我只是在學習,我無法真正弄清楚如何從現有的在線代碼片段中做到這一點。
編輯:這是我在我的views.py得:(你會從「\\」,我是在Windows系統中通知)
def myfiles_page(request):
path = os.path.dirname(os.path.abspath(__file__))
myfiles = os.path.join(path, 'myfiles\\')
os.chdir(myfiles)
x = 0
d = {}
for file in os.listdir("."):
d[x] = (myfiles + file)
x = x + 1
variables = RequestContext(request, {
'user' : request.user,
'filedict' : d,
})
return render_to_response('myfiles_page.html', variables)
這是怎麼了我試圖讓它在模板顯示:(根據Django documentation)
{% for key, value in filedict %}
{{ key }}: {{ value }}
{% endfor %}
但「filedict」仍然沒有顯示在模板中任何東西。有任何想法嗎?
+1爲大胖安全警告。 – 2011-02-02 13:44:27