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
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.
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.
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.
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/...', ...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With