Django:自动生成目录中的文件列表 [英] Django: Auto-generating a list of files in a directory

查看:610
本文介绍了Django:自动生成目录中的文件列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网站上使用了图片库应用。目前我将图像文件放在目录中,并手动为每个图像写入img html标签。是否有可能让django自动在目录中创建一个文件列表,并将json输出发送到gallery应用程序,这样我就可以使javascript生成< img> 每个图像文件的元素。或者,每当请求图库应用时,我是否可以直接让django为目录中的每个文件自动生成< img> 元素。

I use an image gallery app on my website. At present I drop image files in a directory, and write img html tags for each image manually. Is it possible to make django create a list of files in the directory automatically, and send the json output to the gallery app, so that I can make javascript to generate <img> elements for each image files. Or, whenever gallery app is requested, can I directly make django to auto-generate <img> elements for each of the files in a directory.

推荐答案

这里有一些代码供您使用:

here's a bit of code for you:

views.py

import os 

def gallery(request):
    path="C:\\somedirectory"  # insert the path to your directory   
    img_list =os.listdir(path)   
    return render_to_response('gallery.html', {'images': img_list})

gallery.html

gallery.html

{% for image in images %}
<img src='/static/{{image}}' />
{% endfor %}

这篇关于Django:自动生成目录中的文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆