Django:在视图中获取ImageField的URL

31

我正在尝试在Django视图中获取 ImageField 的绝对路径,以便可以打开该图像,在其上写入一些内容,然后将其提供给用户。

我无法获取保存在媒体文件夹中的图像的绝对路径。

item = get_object_or_404(Item, pk=pk)
absolute_url = settings.MEDIA_ROOT + str(item.image.path)

我遇到了错误,提示item.image没有路径 (The 'banner' attribute has no file associated with it.)。 item.image是一个 ImageField ,我想知道如何在 Django 视图中获取保存在图像字段中的图像的绝对路径。

4个回答

47

当配置正确时,使用.urlitem.image.url。在此处查看文档


4
我尝试使用 .url 但它不起作用,在模板中可以使用但在视图中不能 :/ - Byteme
也许是因为我将ImageField扩展为BannerField所致...但我在那里所做的只是覆盖clean方法。 - Byteme
@user2225675 你如何管理图像文件?似乎item.image缺少其相关文件。也许这是由于上传配置错误或您在模板和视图中尝试不同的项目所致? - okm
它在模板和视图中是相同的项目...在模板中它没有问题地显示。“mnge image files” 是什么意思? - Byteme

10

同时,您可以在Django文档中找到相关示例,链接如下:https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FilePathField.path - Peter Rosemann

2
我刚刚弄清楚了问题所在...文件变量中保存了绝对图像路径。
例如(在视图中):
item = Item.objects.get(pk=1)
print item.file # prints out full path of image (saved in media folder)

1
假设图像字段称为照片:
图像 URL
# Image URL
instance.photo.url

# Image Path
instance.photo.path

请在Django的“管理文件”文档中了解更多。

Django 4.1: https://docs.djangoproject.com/en/4.1/topics/files/

在模板中添加图片

 <img src="{{instance.photo.url}}" alt="photo">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接