How to use floatformat in a centralized way in Django

In my project, I ask the user about some measures, prices and weights. I want to store data as a two-digit value. I think I should use DecimalField instead of FloatField because I don't need much precision.

When I print values ​​in my templates, I do not want to print zero significant decimal places.

Examples:

10.00 should show just 10

10.05 should show 10.05

I do not want to use the floatformat filter in every template. I show value, too many places. Therefore, I was wondering if it is possible to somehow influence the value displayed for the entire application in a centralized manner.

thank

+3
source share
3 answers

Finally, I came up with an answer to this question and posted it on my blog: http://tothinkornottothink.com/post/2156476872/django-positivenormalizeddecimalfield

I hope someone finds this useful

0
source

Have you tried the django Humanize plugin ?

You can find there what you are looking for.

Edit

You are right, humanization filters do not do this job here. After digging around the built-in filters and django tags, I could not find anything that would solve your problem. Therefore, I think you need a special filter for this. Sort of...

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 can do something like ...

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

x y, 1.0 1.1 , :

  1
  1.1

, .

+2

, :

_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
0

Source: https://habr.com/ru/post/1773074/


All Articles