Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing image dimensions on an ImageField in a Django template?

I have ImageField in my model and I'm able to display the image in a template. However, how do I retrieve the image's height and width?

like image 836
olegmil Avatar asked Apr 02 '11 10:04

olegmil


People also ask

How can I pass an image to a template in Django?

you can pass your base_image to get_image. html page using dictionary content = {"base_image": base_image} and use {{base_image}} key at src attribute in get_img. html template to display.

What is image field in Django?

ImageField in Django Forms is a input field for upload of image files. The default widget for this input is ClearableFileInput. It normalizes to: An UploadedFile object that wraps the file content and file name into a single object.


2 Answers

See the documentation for ImageField.

In addition to the special attributes that are available for FileField, an ImageField also has height and width attributes.

So just do the following:

<img src="{{ image.url }}" width="{{ image.width }}" height="{{ image.height }}"/> 
like image 100
bradley.ayers Avatar answered Sep 24 '22 16:09

bradley.ayers


In my case, for the width and height fields to work, I need to set the width_field and height_field of the ImageField

E.g.

class Product(models.Model):     image = models.ImageField(width_field='image_width', height_field='image_height')     image_width = models.IntegerField()     image_height = models.IntegerField() 
like image 43
Ron Avatar answered Sep 23 '22 16:09

Ron