31

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

Alasdair
  • 298,606
  • 55
  • 578
  • 516
Byteme
  • 589
  • 2
  • 6
  • 10

4 Answers4

47

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

Ajoy
  • 1,838
  • 3
  • 30
  • 57
okm
  • 23,575
  • 5
  • 83
  • 90
  • 4
    I tried using .url but it doesn't work.. it works in templates but not in view :/ – Byteme Apr 02 '13 at 13:13
  • Maybe it's caused by the fact that I hve extended ImageField into BannerField... but all i've done there is overwritten clean method. – Byteme Apr 02 '13 at 13:15
  • @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? – okm Apr 02 '13 at 13:22
  • 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? – Byteme Apr 02 '13 at 13:45
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?

Peter Rosemann
  • 505
  • 8
  • 20
  • Meanwhile you can find an related example in the Django documentation here: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FilePathField.path – Peter Rosemann Jul 08 '19 at 22:21
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
  • 589
  • 2
  • 6
  • 10
0

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">
alv2017
  • 752
  • 5
  • 14