List directory file contents in a Django template

2024/10/10 22:27:22

I'm just learning Python & Django. (Thanks to everyone who contributes here -- it's been an invaluable resource!)

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 downloadable links. Whether this is secure or not is another question, but suppose I want to do it...

This post helped steer me in the right direction: Python directory list returned to Django template

This code snippet outputs the filenames in 'myfiles' if run from a prompt:

path= os.path.dirname(os.path.abspath(__file__))  
myfiles = os.path.join(path, 'myfiles')  
os.chdir(myfiles)  
for files in os.listdir("."):print files  

But how do I pass these files to a Django template and generate a list of links? I think I may have to create a Python dictionary/tuple of some sort to make it iterable, pass it as a template variable and render it in a for loop?

Do I have to add an entry to my urls.py file to make this work? Something like this?

(r'^myfiles/(?P<path>.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'myfiles'), 'show_indexes': True}),

Thanks for your help! I'm just learning and I couldn't really figure out how to do this from existing code snippets online.

EDIT: This is what I've got in my views.py: (you'll notice from the '\\' that I'm on a Windows system)

def myfiles_page(request):path = os.path.dirname(os.path.abspath(__file__))myfiles = os.path.join(path, 'myfiles\\')os.chdir(myfiles)x = 0d = {}for file in os.listdir("."):d[x] = (myfiles + file)x = x + 1variables = RequestContext(request, {'user' : request.user,'filedict' : d,})return render_to_response('myfiles_page.html', variables)

This is how I was trying to get it to display in a template: (according to the Django documentation)

{% for key, value in filedict %}{{ key }}: {{ value }}
{% endfor %}

But 'filedict' is still not displaying anything in the template. Any ideas?

Answer

Something very much not like that, I reckon.

You'll probably need to create a function of your own inside views.py - see tutorial.

That function will get the file list from os.listdir into a list.

Pass that list in the context to a template and do render_to_response with a template you've written - see tutorial.

In the template, its then something like:

{% for file in filelist %}{{ file }}
{% endfor %}

You can pass anything in the context to a template. You might want to pass an augmented list of files with URLs too - a list of dicts, where each dict has a name and a url. Then your template is:

{% for file in filelist %}<a href="{{file.url}}">{{ file.name }}</a>
{% endfor %}

BIG FAT SECURITY WARNING

Don't let users browse files by letting them put a path in a URL, at least not without really really checking that they can't do stuff like /myfiles/../../notmyfiles/secret.txt and see other peoples files just by sticking dot-dots in the path to go upwards.

If you dont understand that, then you probably shouldn't be coding this up on anything but a toy system that you don't mind being ripped to pieces!

https://en.xdnf.cn/q/69846.html

Related Q&A

Produce PDF files, draw polygons with rounded corners

Whats the right tool for the job if I want to write a Python script that produces vector graphics in PDF format? In particular, I need to draw filled polygons with rounded corners (i.e., plane figures…

How can I unit test this Flask app?

I have a Flask app that is using Flask-Restless to serve an API.I have just written some authentication that checksIf the consumers host is recognised The request includes a hash (calculated by encrypt…

How to completely reset Python stdlib logging module in an ipython session?

Id like to make repeated calls to Python scripts using %run in an ipython session, and for each of those scripts to log based on cmdline arguments passed via %run.For example while debugging cmd.py I m…

I think Librosa.effect.split has some problem?

firstly, this function is to remove silence of an audio. here is the official description:https://librosa.github.io/librosa/generated/librosa.effects.split.htmllibrosa.effects.split(y, top_db=10, *karg…

Replace None in list with leftmost non none value

Givena = [None,1,2,3,None,4,None,None]Id likea = [None,1,2,3,3,4,4,4]Currently I have brute forced it with:def replaceNoneWithLeftmost(val):last = Noneret = []for x in val:if x is not None:ret.append(x…

Generating lists/reports with in-line summaries in Django

I am trying to write a view that will generate a report which displays all Items within my Inventory system, and provide summaries at a certain point. This report is purely just an HTML template by the…

How to test if a view is decorated with login_required (Django)

Im doing some (isolated) unit test for a view which is decorated with "login_required". Example:@login_required def my_view(request):return HttpResponse(test)Is it possible to test that the &…

Filter Nested field in Flask Marshmallow

I want to filter the nested field with is_active column as True in Marshmallow 3 Consider following scenario I have 3 tablesusers (id, name) organizations (id, name) organization_user(id, organization_…

Copy signature, forward all arguments from wrapper function

I have two functions in a class, plot() and show(). show(), as convenience method, does nothing else than to add two lines to the code of plot() likedef plot(self,show_this=True,show_that=True,color=k,…

How to fit a line through a 3D pointcloud?

I have a cable I am dropping from moving vehicle onto the ground. Using a camera system I estimate the location where the rope touches the ground in realtime. Movement of the vehicle and inaccuracy in …