【问题标题】:Django: Auto-generating a list of files in a directoryDjango:自动生成目录中的文件列表
【发布时间】:2011-10-25 21:39:26
【问题描述】:

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

【问题讨论】:

  • 是的,你可以。 Django 是一个 Python,因此您可以使用 Python 算法在目录中创建文件列表,然后使用它来生成元素或使用 'for' 模板标签。

标签: python django image list


【解决方案1】:

这里有一些代码给你:

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})

图库.html

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

【讨论】:

    【解决方案2】:
    import os
    from django.conf import settings
    from annoying.decorators import ajax_request
    
    @ajax_request
    def json_images(request, dir_name):
        path = os.path.join(settings.MEDIA_ROOT, dir_name)
        images = []
        for f in os.listdir(path):
            if f.endswith("jpg") or f.endswith("png"): # to avoid other files
                images.append("%s%s/%s" % (settings.MEDIA_URL, dir_name, f)) # modify the concatenation to fit your neet
        return {'images': images}
    

    此函数返回一个 json 对象,其中包含 MEDIA_ROOT 内目录中的所有图像。

    需要 django-annoying 软件包 ;)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-16
      相关资源
      最近更新 更多