【问题标题】:Can't load static image in django when using a loop使用循环时无法在 django 中加载静态图像
【发布时间】: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'],然后在模板中`简单地循环该数组并使用&lt;img src="{% static '{{ operatorimg_url }}' %}"&gt;显示它。
  • 但它最终会在那个文件夹中有 30 多张照片,这是唯一的方法吗?
  • 统计文件用作不会更改的文件,例如某些背景图像、css 文件、js 文件等。如果您有动态文件,例如需要更新和动态添加的配置文件图像然后将其视为媒体文件。

标签: python django for-loop


【解决方案1】:

答案可能因您使用的 Django 版本而异。

对于 Django 3.0,以下应该可以工作

# settings.py

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    'static',
]

然后在模板内-

{% load static %}

<img src="{% static '{{ operator.url }}' %}">

我猜图片可能会出现以下内容-

<img src="{{ operator.url }}">

【讨论】:

    猜你喜欢
    • 2020-04-02
    • 2016-12-30
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2011-08-06
    • 2011-12-04
    相关资源
    最近更新 更多