Reputation: 1371
I have a model with DecimalField
:
points_player1 = models.DecimalField(max_digits=3, decimal_places=1, blank=True, null=True)
When I displaying this field in template, it always shows values like 0.0
or 1.0
etc.
But I want to make this behavior more user-friendly:
1
it displays 1
(now its 1.0).1.5
it should displays 1.5
.0
, not 0.0
.What is the best way to make this? Is DecimalField
is right choice for my case?
Upvotes: 4
Views: 12121
Reputation: 14508
Create a new model field
class DecimalFieldNormalized(models.DecimalField):
def from_db_value(self, value, *args):
if value is None:
return value
return value.normalize()
Upvotes: 0
Reputation: 53386
You can do {{decimal_field|floatformat}}
in the template, which will round off and show ".0" only when necessary.
More reference template - floatformat
Upvotes: 14
Reputation: 1593
Also you can modify the model save method if for some reason you can't/don't want to use django templating, adding this to the bottom of your model:
def save(self, *args, **kwargs):
self.points_player1 = float(self.points_player1)
super(YourModelName, self).save(*args, **kwargs)
Didn't tryed it , but it should work.
Upvotes: -1