Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django. Listing files from a static folder

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.

enter image description here
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

like image 824
Ilja Leiko Avatar asked Oct 11 '17 14:10

Ilja Leiko


People also ask

How show static files Django?

Configuring static filesMake sure that django.contrib.staticfiles is included in your INSTALLED_APPS . In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE . Store your static files in a folder called static in your app.

Where are static files Django?

STATIC_URL is the URL location of static files located in STATIC_ROOT. STATICFILES_DIRS tells Django where to look for static files in a Django project, such as a top-level static folder. STATIC_ROOT is the folder location of static files when collectstatic is run.

How do you serve a static file?

To serve static files such as images, CSS files, and JavaScript files, use the express. static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets.


1 Answers

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/...', ...]
like image 92
user2390182 Avatar answered Oct 12 '22 11:10

user2390182