【问题标题】:Failing To Display Media File Django无法显示媒体文件 Django
【发布时间】:2020-04-18 22:33:34
【问题描述】:

我创建了一个名为 Product 的模型,该模型接受一个 ImageField,该模型将上传到我创建的函数中:

class Product(models.Model):

title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=10, default=39.99)
image = models.ImageField(upload_to=upload_image_path, null= True, blank=True)

def __str__(self):
    return self.title
    return self.image

def __unicode__(self):
    return self.title

我还创建了我的 MEDIA_ROOT 和 STATIC_ROOT 下面是来自主 url 的代码,但是我也在 settings.py 中定义了这两个:

if settings.DEBUG:
    urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

所以我可以从管理员上传图片,并正确上传到我创建的 media_root。

当我尝试调用/显示图像时,它什么也不渲染我不知道我可能在哪里犯了错误

{% load static %}
{{ object.title }} <br/>
{{ object.description }} <br/>
{{ object.image.url }}<br/>
<img src="{{ object.image.url }}" class='img-fluid'/>

{{ object.image.url }} 实际上给了我图像的确切路径,这对于要渲染的图片应该是有意义的。

This is the the result output that I was telling about, that I'm getting the image url but I can not display the Image

【问题讨论】:

    标签: django django-models django-media


    【解决方案1】:
    <img src="/media/{{ object.image }}" alt='xyz'>
    

    【讨论】:

    • 当我这样做(&lt;img src="/media/{{ object.image }}" alt='xyz'&gt; 代码同时渲染 alt='xyz'上传
    • 在 GitHub 上上传你的项目并给我发一个链接。
    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常质量更高,更有可能吸引投票。
    • @Mr.kn1 这里是github上项目的链接github.com/CrazyTeddy1/eCommerce
    • 我看不懂你的代码但别担心,去这个链接看看如何渲染图像 Link = drive.google.com/file/d/1BAw8Me4HRf5zY6jLjyzGRXbJCIywGtcS/view
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-17
    • 2018-08-27
    • 1970-01-01
    • 2015-07-18
    • 2020-04-12
    • 2020-01-15
    • 2021-01-30
    相关资源
    最近更新 更多