2017-10-11 48 views
1

我遇到的一个看似基本的问题是将一个简单的静态文件列表(例如我的服务器上的单个存储库目录的内容)作为链接列表呈现。这是否安全是另一个问题,但假设我想这样做...... 这就是我的工作目录的样子。我想列出模板中分析文件夹的所有文件,作为链接。Django。列出来自静态文件夹的文件

enter image description here
我试图访问静态文件view.py以下一些tutorial和有它这样的:

view.py

from os import listdir 
from os.path import isfile, join 
from django.contrib.staticfiles.templatetags.staticfiles import static 


def AnalyticsView(request): 
    mypath = static('/analytics') 
    allfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] 

    return render_to_response('Rachel/analytics.html', allfiles) 

而且我的模板:

<p>ALL FILES:</p> 
{% for file in allfiles %} 
    {{ file }} 
    <br> 
{% endfor %} 

而我的settings.py

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) 
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') 
STATIC_URL = '/static/' 
STATICFILES_DIRS = [ 
    os.path.join(BASE_DIR, "static"), 
] 

,我得到的错误:

FileNotFoundError at /analytics/ 
[WinError 3] The system cannot find the path specified: '/analytics' 

错误traceback 任何帮助将是非常赞赏

+0

我想你看错了教程。 '''static'''会为静态资源生成一个url,而不是文件路径。所以你应该遍历你的文件系统并为每个文件调用static来生成链接,你应该把它放到网页 –

回答

1

它的工作原理!这里是一个更好的方法:

import os 

def AnalyticsView(request): 
    path="E:\\Development\\Information_Access_Project\\Information_Access_Project\\static\\analytics" # insert the path to your directory 
    analytics_list =os.listdir(path) 
    return render_to_response('Rachel/analytics.html', {'analytics': analytics_list}) 

,并在模板

{% for analytic in analytics %} 
    <a href="/static/analytics/{{ analytic }}">{{ analytic }}</a> 
    <br> 
{% endfor %} 
0

我没有一个Django ENV尝试了这一点,但尝试(像)这个:

def AnalyticsView(request): 
    mypath = 'static' 
    allfiles = [static(f) for f in listdir(mypath) if isfile(join(mypath, f))] 

    return render_to_response('Rachel/analytics.html', allfiles) 
+0

谢谢你的贡献,Alex。我曾尝试过,但它仍然显示出同样的错误。 “FileNotFoundError at/analytics/ [WinError 3]系统无法找到指定的路径:'static'”并为该行辩论“allfiles = [static(f)for listdir(mypath)if iffile(join(mypath, f))]“ –

+0

这可能是因为你没有替换'''mypath''的值:)。 –