【发布时间】:2020-04-26 14:36:33
【问题描述】:
当我使用 for 循环时,我无法在 django 中加载图像,如果我为每个文件指定路径,图像将加载。
作品:
当我尝试使用循环时,它不会加载图像。
view.py:
operators = []
directory =
os.path.join(os.path.join(os.path.join(os.path.join(settings.BASE_DIR)
,'static'),'images'),'operators')
for file in os.listdir(directory):
if file.endswith(".png") or file.endswith(".jpg"):
operators.append(file)
然后我尝试使用上下文返回图像。
html 文件:
{% if operators %}
There are {{ operators|length }} records:
{% for operator in operators %}
<div class="media">
<img src="{{operator}}" class="align-self-center mr-3" alt="...">
</div>
{{operator}}
{% endfor %}
{% else %}
There are no records in the system
{% endif %}
如果有人知道如何修复我的代码,那就太棒了。
settings.py:
STATIC_URL = '/static/'
# Pointing django to the static file location.
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'static'),
)
【问题讨论】:
-
算子里有多少张图片?
-
文件夹中只有 2 张图片
-
那么不要使用该视图循环逻辑(它不会工作,因为当您部署应用程序时,您的静态目录将被更改,并且它也存在安全问题)。只需传递
['images/operators/image1.jpeg','images/operators/image2.png'],然后在模板中`简单地循环该数组并使用<img src="{% static '{{ operatorimg_url }}' %}">显示它。 -
但它最终会在那个文件夹中有 30 多张照片,这是唯一的方法吗?
-
统计文件用作不会更改的文件,例如某些背景图像、css 文件、js 文件等。如果您有动态文件,例如需要更新和动态添加的配置文件图像然后将其视为媒体文件。