Django:在视图中获取ImageField网址

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

我在获取保存在媒体文件夹中的图像的绝对路径时遇到问题。

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

I get error, that item.image does not have path (The 'banner' attribute has no file associated with it.). item.image is ImageField and I'd like to know how to get absolute path of the image saved in image field (within Django view).

最佳答案

When configured correctly, use .url: item.image.url. Check the docs here.