Django - Render a List of File Names to Template

谁都会走 提交于 2020-05-17 04:33:29

问题


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


回答1:


Your dictionary is not a valid python code because you are using "=" instead of ":". It should be:

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

One last thing, listdir expects an abosulte path, you can get the root path of your project with:

ROOT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8')).replace('\\', '/') 



回答2:


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.



来源:https://stackoverflow.com/questions/8304547/django-render-a-list-of-file-names-to-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!