我有一个具有图像字段的模型
profile_picture = models.ImageField(upload_to='clothes_images', null=True, blank=True)
。
我有一个返回图像 URL 的函数
def image_url(self):
if self.profile_picture:
return self.profile_picture.url
return None
但是当我使用此代码在模板中显示时
<img src="{{cloth.image_url}}">
我收到此错误Not Found: /media/clothes_images/1_fSqDIIb.png
我的图像名称是 1.png,但当我存储它并且找不到它时它会发生变化。
我想显示存储在本地系统中的每个图像。 这是我的媒体设置.py 文件
MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
我还将此代码添加到我的 urls.py 文件中
if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
如果您将图像存储为
base64
编码到数据库中,您可以将其显示为 html:
# pip install pybase64
import base64
with open("image.jpg", "rb") as imagefile:
convert = base64.b64encode(imagefile.read())
print(convert.decode('utf-8'))
# in html page the tag for showing the image looks like
# <img src="data:image/png;base64,iVBORw0KG..." />