Django. Listing files from a static folder

て烟熏妆下的殇ゞ 提交于 2020-07-06 20:35:28

问题


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.


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)

And my template:

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

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"),
]

And i am getting the error:

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

Error traceback Any help will be very appreciated


回答1:


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/...', ...]



回答2:


I don't have a django env to try this out, but try (something like) this:

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)



回答3:


It works! Here is a better approach:

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})

and in template

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


来源:https://stackoverflow.com/questions/46691544/django-listing-files-from-a-static-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!