【问题标题】:How do I load an image into the img tag from a python field?如何从 python 字段将图像加载到 img 标签中?
【发布时间】:2021-10-17 00:42:00
【问题描述】:

我目前正在使用jinja 在 HTML 中加载一个对象,如下所示

<span> {{ object.name }} </span>
<img src = "{{ object.image }}" >

image 字段是数据库中的 ImageField。图片网址如下所示

http://127.0.0.1:8000/uploads/testimage.png

如何在&lt;img&gt; 标签中正确渲染图像?

【问题讨论】:

  • &lt;img src="{{ object.image.url }}" &gt;
  • 返回以下问题:The 'image' attribute has no file associated with it.
  • 那么您需要保护图像,使其仅在object.image 真实时才呈现。

标签: html django django-models jinja2


【解决方案1】:

图片网址如下所示

http://127.0.0.1:8000/uploads/testimage.png

这是不是图像 URL,这个{{ object.image }} 呈现您指定的媒体目录中图像的路径。但是(可能)没有视图听这个视图。

为了渲染图像,您使用FieldFile 对象的.url 属性,所以:

<span> {{ object.name }} </span>
{% if object.image %}<img src="{{ object.image.url }}">{% endif %}

您还应该配置urls.py 来处理对这些媒体文件的请求。这在the serving files uploaded by a user during development section of the documentation中有解释:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # …
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

请注意,Django 在生产中提供媒体/静态文件。在这种情况下,您需要配置网络服务器,如 nginx/apache/...

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多