Django: Get ImageField url in view
Asked Answered
E

4

33

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

Emaemaciate answered 2/4, 2013 at 12:51 Comment(0)
M
49

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

Mcgill answered 2/4, 2013 at 12:58 Comment(4)
I tried using .url but it doesn't work.. it works in templates but not in view :/Emaemaciate
Maybe it's caused by the fact that I hve extended ImageField into BannerField... but all i've done there is overwritten clean method.Emaemaciate
@user2225675 How do you manage image files? Seems item.image is missing its relative file. Perhaps it was caused by mis-configuration of uploading or you are trying different items in template and view?Mcgill
It's the same item in template and the view.. in template it shows w/o problem. What do you mean by mnge image files?Emaemaciate
M
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?

Mefford answered 2/4, 2013 at 15:30 Comment(1)
Meanwhile you can find an related example in the Django documentation here: docs.djangoproject.com/en/dev/ref/models/fields/…Mefford
E
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)
Emaemaciate answered 2/4, 2013 at 16:39 Comment(0)
W
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">
Worldling answered 6/3, 2023 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.