Django的。列出静态文件夹中的文件 [英] Django. Listing files from a static folder

查看:251
本文介绍了Django的。列出静态文件夹中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

One seemingly basic thing that I'm having trouble with is rendering a simple list of static files (say the contents of a single repository directory on my server) as a list of links. Whether this is secure or not is another question, but suppose I want to do it... That's how my working directory looks like. And i want to list all the files fro analytics folder in my template, as links.


< br>我已尝试按照教程,如下所示:


view.py


I have tried accessing static files in view.py following some tutorial and having it like that:

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

And my 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'

错误回溯
任何帮助将不胜感激

Error traceback Any help will be very appreciated

推荐答案

遇到类似问题,并使用django实用程序找到以下解决方案:

Came across a similar issue and found the following solution using django utilities:

from django.contrib.staticfiles.utils import get_files
from django.contrib.staticfiles.storage import StaticFilesStorage

s = StaticFilesStorage()
list(get_files(s, location='analytics'))
# ['analytics/report...', 'analytics/...', ...]

这篇关于Django的。列出静态文件夹中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆