【问题标题】:How to display files from a folder in django如何在django中显示文件夹中的文件
【发布时间】:2017-03-06 04:51:47
【问题描述】:

我制作了一个文件夹中包含图像的 django 应用程序。我必须创建一个下拉菜单来选择它必须选择的图像。必须提供文件夹的路径,并且该图像应该显示在 html 中页。

【问题讨论】:

    标签: html django file file-upload


    【解决方案1】:

    问题是经过修改的版本: Django: Auto-generating a list of files in a directory

    (致谢:@Hoff 已接受上述帖子的答案):

    代码:

    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】:

      这是对 Fakkabir 答案的修改,并假设您尝试加载的图像可通过 /static/ 获得

      views.py

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

      图库.html

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

      【讨论】:

        猜你喜欢
        • 2010-09-20
        • 2011-06-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-06
        • 2021-04-29
        • 2019-05-22
        相关资源
        最近更新 更多