检索django中的所有静态图像

时间:2018-03-26 11:47:37

标签: django

在我的django应用程序中我有一个javascript模态。在那个模态中我想显示所有可用的静态图像。我知道是否有单个图像我们可以显示 它是

{% load static %}
      <img src="{% get_static_prefix %}images/abc.png">

但我想动态显示所有图像(它们不是固定的)。如何为此编写循环。

我想要的输出(循环应生成此输出)

{% load static %}
      <img src="{% get_static_prefix %}images/abc.png">
      <img src="{% get_static_prefix %}images/def.png">
      <img src="{% get_static_prefix %}images/ghi.png">
      .
      .
      .
      <img src="{% get_static_prefix %}images/xyz.png">

更新1 我的views.py

def show_images(request):

    image_list=[]
    image_folder = settings.STATICFILES_DIRS  #you can add the subdirectory here as well with os.path.join
    for file in image_folder:
        if file.endswith(".png"):
            image_list.append(file)
    # TODO: Read list of existing Int Files and send data to feed the table
    return render(request, myapp/showimages.html', {'brands': image_list})

我的模板:

{% for file in brands %}
        <img src="{{file}}" alt="">
    {% endfor %}      

但有了这个,我无法加载图片

3 个答案:

答案 0 :(得分:1)

您可以从视图中发送上下文中的所有静态图像。

import os
image_list=[]
for root, dirs, files in os.walk(settings.STATIC_ROOT):
    for file in files:
        if file.endswith(".png"):
            image_list.append(file)

如果要遍历整个静态目录,可以执行以下操作:

image_list

然后,您可以在上下文中返回import os image_list=[] app_static_dir = os.path.join(os.path.join(os.path.join(os.path.join(settings.BASE_DIR,'appname'),'static'),'images'),'brands') #appname is your appname and brands is the folder that you mentioned for file in os.listdir(app_static_dir): if file.endswith(".png"): image_list.append(file) 并在模板中迭代它。

更新: 对于特定应用中的所有静态文件,您可以执行以下操作:

type

答案 1 :(得分:0)

在uploadApp应用程序中,我有:view.py,displayImg.html。

view.py

def uploadImg(request):
    image_list=[]
    for root, dirs, files in os.walk(settings.MEDIA_ROOT):
        for file in files:
            image_## Heading ##list.append(file)
    return render(request, 'displayImg.html',{'brands': image_list})
#complete.html

displayImg.html

{% load static %}
{% block content %}    
    {% for file in brands %}
        <img src="{% get_media_prefix %}{{ file }}" width="500px" />
    {% endfor %} 
    {% endblock %}

在settings.py中:

MEDIA_ROOT = os.path.join(BASE_DIR, 'your path to upload images') 

答案 2 :(得分:0)

view.py

def uploadImg(request):
    
    image_list=[]

    for root, dirs, files in os.walk(settings.MEDIA_ROOT):
        for file in files:
            image_list.append(file)
    return render(request, 'displayImg.html',{'brands': image_list})

displayImg.html

{% load static %}
{% block content %}    
    {% for file in brands %}
        <img src="{% get_media_prefix %}{{ file }}" width="500px" />
    {% endfor %} 
    {% endblock %}

在sittings.py中:MEDIA_ROOT = os.path.join(BASE_DIR,“您上传图片的路径”)