Search code examples
pythondjangodjango-templatesdjango-viewstwisted

Django - Render a List of File Names to Template


I am generating a template for an image gallery page. My approach is as follows:

  • Host the images from a sub directory of an images folder
    • The image folder will be titled the same as the gallery title
  • The view passes a list of filenames to the template
  • The template loops through the list and creates img tags

So my view would be

def some_gallery(request):
    #LOGIC TO GET A LIST OF FILENAMES

    variables = RequestContext(request,{
        'user' : request.user,
        'title' : 'something',
        'files' : fileList
    })
    return render_to_response('gallery_template.html',variables)

And the template

....
{% for file in files %}
    <img src="/path/to/images/{{ title }}/{{ file }}">
{% endfor %}
....

The problem I am running into is that Django is putting up a 500 error when I try to use the os.listdir function. How can I get the file list that I need??

Problematic version of the view which is giving the 500 error

def some_gallery(request):

    variables = RequestContext(request,{
        'user' : request.user,
        'title' : 'something',
        'files' : os.listdir('/path/to/gallery')
    })
    return render_to_response('gallery_template.html',variables)

Also I should note that the file path does work, so if I go directly to the url, I get just the image as expected.

EDIT: Fixed the typos in code samples


Solution

  • I got it sorted out. My methods were correct, so anyone looking to do this type of thing, the code samples should work.

    The problem that I had was that Django was tripping up on the listdir function call due to some problems accessing the file path that was provided. I made sure the directory permissions and path was correct and it worked.

    Thanks to those that helped.