[Django]-How to use floatformat in a centralized way in Django

1👍

I finally came up with the answer to this question and posted it in my blog:
http://tothinkornottothink.com/post/2156476872/django-positivenormalizeddecimalfield

I hope somebody finds it useful

2👍

Have you tried the django plugin Humanize ?

You might find there what you’re looking for.

Edit

Your are right, humanize filters don’t do the job here.
After digging around the django built-in filters and tags I couldn’t find anything that solves your issue. Therefore, I think you need a custom filter for this. Something like …

from django import template

register = template.Library()

def my_format(value):
    if value - int(value) != 0:
        return value
    return int(value)

register.filter('my_format',my_format)
my_format.is_safe = True

And in your django template you could do something like …

{% load my_filters %}
<html>
<body>
{{x|my_format}}
<br/>
{{y|my_format}}
</body>
</html>

For values x and y, 1.0 and 1.1 respectively that would show:

  1
  1.1

I hope this helps.

0👍

How about a property in the model in such way that:

_weight = models.DecimalField(...)
weight = property(get_weight)

def get_weight(self):
    if self._weight.is_integer():
        weight = int(self._weight)
    else:
        weight = self._weight
    return weight

Leave a comment