How to use floatformat in a centralized way in Django
In my project I'm asking the user for some measures, prices and weights. I want to store data as a two decimal value. I guess I should be using DecimalField instead of FloatField, because I don't need much precision.
When I print values in my templates, I don't want zero non si开发者_Python百科gnificant decimals to be printed.
Examples:
10.00 should show simply 10
10.05 should show 10.05
I don't want to use floatformat filter in every template I display the value, too many places. So I was wondering if there is some way to affect the value rendered for all the application, in a centralized manner.
Thanks
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.
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
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
精彩评论