Liam Chapman
Liam Chapman

Reputation: 140

Django Model/Template Arithmetic Issue

I'm kinda new to Django and I'm trying to do some simple math to work out a ratio of an image. In my model I upload a header image, which also stores the width and height.

Using these values I create a ratio to be used on the frontend. When I show this value it returns 0. I have also tried using filters such as floatformat and it does nothing.

My Image dimensions are - Width: 1920px, Height: 1098.

I'm generating the ratio like so:

height / width.

I expect a value of: 0.571875

As mentioned previously it just returns 0 when on the frontend. If I use floatformat it just returns 0.00 etc.. I know the values are there because they are returned ok.

Here is some example code used in my Model:

class Article(models.Model):
    header_width     = models.IntegerField(default=1)
    header_height    = models.IntegerField(default=1)
    header           = models.ImageField(width_field='header_width',height_field='header_height')

    def ratio (self):
        return self.header_height / self.header_width

Then in my template I'm doing something like this:

<img src="{{ MEDIA_URL }}{{ article.header }}" data-ratio="{{ article.ratio }}" alt="header image">

Hopefully that is enough info. If not, I'll try and add more if you need it.

Thanks!

Upvotes: 0

Views: 115

Answers (1)

301_Moved_Permanently
301_Moved_Permanently

Reputation: 4186

Using python 2.7, the / operator performs an integer division when both operand are integer. You most likely want to write:

return float(self.header_height) / float(self.header_width)

Upvotes: 2

Related Questions