【问题标题】:Django - possible to display ImageField objects in static folder?Django - 可以在静态文件夹中显示 ImageField 对象吗?
【发布时间】:2014-03-28 13:28:22
【问题描述】:

这是我的 settings.py:

STATIC_URL = '/static/'

# Additional locations of static files
 STATICFILES_DIRS = (
    '/home/userName/project/app/static',
)

假设我的视图将 ImageField 对象传递给模板。因此,如文档中所述:

https://docs.djangoproject.com/en/1.5/ref/models/fields/#django.db.models.fields.files.FieldFile.url

我可以通过这样做访问图像的 URL

 {{ FieldFile.url }}

在我的模板中。如果我尝试访问图像的 URL,它可以工作,但是,我也需要能够加载静态。我想做这样的事情:

{% load staticfiles %}

<img src="{% static "{{ FieldFile.url }}" %}" alt="" />

但是,这不起作用。假设 FieldFile.url 是

images/imageName.jpg

当我这样做时

<img src="{% static "images/imageName.jpg" %}" alt="" />

可以,但是我用的时候就不行了

{{ FieldFile.url }}

不知为何,怎么会?

注意:当我尝试做时

{% load staticfiles %}

<img src="{% static "{{ FieldFile.url }}" %}" alt="" />

并使用谷歌浏览器“检查元素”,它显示了这一点

<img src="/static/%7B%7B%20FieldFile.url%20%7D%7D" alt="" />

【问题讨论】:

    标签: django django-templates django-views django-staticfiles django-models


    【解决方案1】:

    {{ }} 不是必需的,因为您已经在模板标签中:

    <img src="{% static FieldFile.url %}" alt="" />
    

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 2021-11-03
      • 1970-01-01
      • 2020-06-21
      • 2013-09-14
      相关资源
      最近更新 更多