【问题标题】:How can I return image address to Django template from a function of the file views.py?如何从文件views.py的函数中将图像地址返回给Django模板?
【发布时间】:2022-01-23 14:07:21
【问题描述】:

我需要使用 Django 模板显示图像,但不知道如何从文件 views.py 的函数中返回“图像地址”

图片地址会根据项目的“id”存储(一个项目有与之关联的图片)。

这是我正在编写的 views.py 文件的功能:-

def file_path(request, awp_id):
    Component_Progress_Update_inst = get_object_or_404( Component_Progress_Update, pk=awp_id)
    filepath = Component_Progress_Update_inst.Supporting_documents.name
    filepath = "/media/"+filepath
    print(filepath)
    # Returning the file path
    return HttpResponse(filepath)

下面是图片标签,我写的是HTML文件:-

<img src="{% url 'component_progress:file_path' awp.id %}" alt="Supporting image" width="200" height="200">

但是图像没有显示出来,而不是图像这个“替代文本”被打印出来了。

虽然我尝试直接显示图像 -> 通过直接在图像“src”中写入该地址。

【问题讨论】:

    标签: python django django-views django-templates


    【解决方案1】:

    也许试试: src="{{object.image.url}}"

    使用 image.url 你可以得到图片的路径。

    【讨论】:

      【解决方案2】:

      我们只需要修改return line,应该如下:-

      return HttpResponseRedirect(filepath)
      

      使用后效果很好!!

      【讨论】:

        猜你喜欢
        • 2014-12-03
        • 2021-01-25
        • 1970-01-01
        • 2012-04-07
        • 1970-01-01
        • 2021-03-06
        • 1970-01-01
        • 1970-01-01
        • 2013-07-10
        相关资源
        最近更新 更多