小编fie*_*red的帖子

列出Django模板中的目录文件内容

我只是在学习Python和Django.(感谢所有在这里做出贡献的人 - 这是一个非常宝贵的资源!)

我遇到的一个看似基本的问题是将一个简单的静态文件列表(比如我服务器上单个存储库目录的内容)呈现为可下载链接列表.这是否安全是另一个问题,但假设我想这样做......

这篇文章帮助我指导了正确的方向: Python目录列表返回到Django模板

如果从提示符运行,此代码段将输出'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  
Run Code Online (Sandbox Code Playgroud)

但是如何将这些文件传递给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}),
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!我刚刚学习,我无法从网上现有的代码片段中找到如何做到这一点.

编辑:这是我在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)
Run Code Online (Sandbox Code Playgroud)

这就是我试图让它在模板中显示的方式:(根据Django文档)

{% for …
Run Code Online (Sandbox Code Playgroud)

python filesystems django repository django-templates

7
推荐指数
1
解决办法
1万
查看次数