Hepri
Hepri

Reputation: 217

Django strange DecimalField validation

I got validation error when it shouldn't be raised. Here is the example:

from django.db.models import DecimalField

f = DecimalField(max_digits=9, decimal_places=3)

# got validation error here
# `Ensure that there are no more than 3 decimal places`
f.clean(value=12.123, model_instance=None)

# returns Decimal('12.1230000')
f.to_python(12.123)

# this is absolutely fine
f.clean(value=123456.123, model_instance=None)

# returns Decimal('123456.123')
f.to_python(123456.123)

Apparently, Django DecimalField uses wrong implementation of to_python which return excessive amount of trailing zeros at the end, and then validation fails.

What could be done with that?

Upvotes: 1

Views: 1397

Answers (1)

Karim N Gorjux
Karim N Gorjux

Reputation: 3033

You must pass the values as string not as a float. Check this out

from django.db.models import DecimalField

f = DecimalField(max_digits=9, decimal_places=3)
f.clean(value="12.123", model_instance=None)
f.to_python("12.123")
f.clean(value="123456.123", model_instance=None)
f.to_python("123456.123")

Upvotes: 2

Related Questions