Limit django FloatField to 2 decimal places

I am looking for a way to limit FloatField in Django to 2 decimal places, and has anyone figured out how to do this without using DecimalField.

I tried decimal_places=2, but it just gave me a migration error inside the float field, so I think this method should only work in DecimalFields.

+8
source share
3 answers

If you are only interested in how your FloatFieldform is displayed, you can use a filter template . floatformat

From Django Docs:

, floatformat .

, value = 34.23234, :

{{ value|floatformat:2 }}  # outputs 34.23
+27

, , , . , .

class MyDataModel(models.Model):
    my_float = models.FloatField()

    def save(self, *args, **kwargs):
        self.my_float = round(self.my_float, 2)
        super(MyDataModel, self).save(*args, **kwargs)

, , , . .

+4

Django 1.8+ FloatField/ ModelFields:

def validate_decimals(value):
    try:
        return round(float(value), 2)
    except:
        raise ValidationError(
            _('%(value)s is not an integer or a float  number'),
            params={'value': value},
        )

... and in your model you can apply it as follows:

from django.db import models

class MyModel(models.Model):
    even_field = models.FloatField(validators=[validate_decimals])
0
source

All Articles