[Django]-Django: Get ImageField url in view

47👍

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

👤okm

10👍

Maybe this way?

@property
def get_absolute_image_url(self):
    return "{0}{1}".format(settings.MEDIA_URL, self.image.url)

see How can I get a list of absolute image URLs from a Django QuerySet?

2👍

I just figured out what was the problem… absolute image path is saved in file variable.

Example (in view):

item = Item.objects.get(pk=1)
print item.file # prints out full path of image (saved in media folder)
👤Byteme

1👍

Suppose that the image field is called photo:

Image URL

# Image URL
instance.photo.url

# Image Path
instance.photo.path

Find out more in the Django "Managing Files" documentation.

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

Add Image to Template

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

Leave a comment