繁体   English   中英

如何将图像从 URL 传递到 Django 模板?

[英]How do I pass an image from URL to a Django template?

我有以下观点:

import requests

def home(request):
    r = requests.get("https://via.placeholder.com/150")

    # Use the headers (r.headers) for something here
    ...

    return render(request, 'index.html', {'image': r.content})

然后在模板中,我想在<img>标签中使用图像,如下所示:

<img src="{{ image }}">

不幸的是,图像在模板中损坏了。 打印r.content ,我得到以下信息:

>>> r.content
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x96\x00\x00\x00\x96\x04\x03\x00\x00\x00\xce/l\xd1\x00\x00\x00\x1bPLTE\xcc\xcc\xcc\x96\x96\x96\xaa\xaa\xaa\xb7\xb7\xb7\xc5\xc5\xc5\xbe\xbe\xbe\xb1\xb1\xb1\xa3\xa3\xa3\x9c\x9c\x9c\x8b*p\xc6\x00\x00\x00\tpHYs\x00\x00\x0e\xc4\x00\x00\x0e\xc4\x01\x95+\x0e\x1b\x00\x00\x01\x00IDATh\x81\xed\xd21o\x830\x18\x84\xe1\x8b1&\xa3\t\xb4s\x93!3\xde:\xc2\xd0\x9d\xaa\x1d\x18\x89\x84P\xc6D\x91\x98QR\xa9\xfd\xd9\xfd\x0ci;\x9b\xb5\xf7\x8c\x87\xf4\x06\x1c\x03DDDDDDDDDD\xb4\x82I\xd3\x16\xc7\xdb\xdfd\xa7\xc9|\x15\xa1\xad-\xd4\xd0\xd7\xd1\xe3\xa1\xfcY\x94\x9d&\xd7\xe7\x81)\x97"\x91\xdfOZ\xd5\xc2\xe4:\x03\xa2\xd4N\xd3\x80}`\xeb\xc5!y\x97/-\xa3\x11\xb8\xaa\x13\xa0\xdf\xec4\xe5x\x0el\xa1\xc2\xea\xbcAU\xc6\xd2r\xae\x96E[?\xe9\x1c\xcd\x82V\xd7\xb4\x95/ \xd9\xe0\xde\xea\x9a\xce\xca\xa3\xe0\x96\x1c\xd18\xbf\x97\xc9\xee-\x99>\x16\xbd\x17\x10\xdb\xf9\xbc\xd6\x9f\xbf\xad\xd8.:/\x07s\x92\xff\xf1\t8\xbe\x16s\xcbO\x03v\xe1\xad\xf5\xe5P\xc8\xfd\xaa\xa135\xce-?\xb9\xfe!\xbc\x15\x9f\xe5\xce\xfb{\xafF\x7f\xbf|\xcbO\x0b\xee=\x11\x11\x11\x11\x11\x11\x11\x11\x11\xfd?\xdfY\xa5%Q\x8a\xf0\x7f\xae\x00\x00\x00\x00IEND\xaeB`\x82'

我需要做什么来格式化内容以在我的模板中可用? 谢谢你的帮助!

编辑

我知道 URL 可以直接在<img>标签中使用。 但是,我需要来自 Python 代码中 URL 的特定标头,这样我就可以保存一个额外的请求。

您可以将 URL 本身作为图像的src="…"传递,因此:

<img src="https://via.placeholder.com/150">

另一种选择是使用 base64 编码,从而使用以下方式对其进行编码:

from base64 import b64encode
import requests

def home(request):
    r = requests.get("https://via.placeholder.com/150")
    return render(request, 'index.html', {'image': b64encode(r.content).decode()})

然后在模板中渲染它:

<img src="data:image/png;base64,{{ image }}">

MIME 类型(此处为image/png )可能会有所不同,具体取决于您发出请求的服务器所使用的图像格式。

暂无
暂无

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

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