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 = 0
d = {}
for file in os.listdir("."):
d[x] = (myfiles + file)
x = x + 1
variables = 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?