繁体   English   中英

如何从文件views.py的function将图像地址返回到Django模板?

[英]How can I return image address to Django template from a function of the file views.py?

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

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

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

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 ”中写入该地址。

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

使用 image.url 您可以获得图像的路径。

我们只需要更改返回线,它应该如下:-

return HttpResponseRedirect(filepath)

使用后效果很好!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM