Django-将文件名列表呈现给模板 [英] Django - Render a List of File Names to Template
问题描述
我正在为图库页面生成模板。我的方法如下:
I am generating a template for an image gallery page. My approach is as follows:
- 从图像文件夹
- 图像文件夹的标题将与画廊标题相同
的子目录中托管图像
所以我的观点是
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)
和模板
.... {% for file in files %} <img src="/path/to/images/{{ title }}/{{ file }}"> {% endfor %} ....
我的问题遇到的是,当我尝试使用os.listdir函数时,Django出现500错误。如何获取所需的文件列表?
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??
视图的问题版本给出500错误
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)
另外,我应该注意文件路径确实有效,所以如果我直接进入url,我会得到只是预期的图像。
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.
编辑:修复了代码示例中的错字
Fixed the typos in code samples
推荐答案
我弄清楚了。我的方法是正确的,所以任何想做这种事情的人,代码示例都可以工作。
I got it sorted out. My methods were correct, so anyone looking to do this type of thing, the code samples should work.
我遇到的问题是Django在listdir上跳闸了由于访问提供的文件路径时遇到一些问题而导致函数调用。我确保目录权限和路径正确,并且可以正常工作。
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.
这篇关于Django-将文件名列表呈现给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!