Accessing image dimensions on an ImageField in a Django template?

青春壹個敷衍的年華 提交于 2019-12-03 16:20:55

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5522611/accessing-image-dimensions-on-an-imagefield-in-a-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!