Byteme
Byteme

Reputation: 629

Django: Get ImageField url in view

I am trying to get ImageField absolute path in Django view so I can open the image, write on it something and then serve it to user.

I have problem getting absolute path for the image which is saved in media folder.

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).

Upvotes: 33

Views: 75593

Answers (4)

alv2017
alv2017

Reputation: 850

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">

Upvotes: 1

Peter Rosemann
Peter Rosemann

Reputation: 505

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?

Upvotes: 10

okm
okm

Reputation: 23871

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

Upvotes: 49

Byteme
Byteme

Reputation: 629

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)

Upvotes: 2

Related Questions