I have a model field full_time_equivalent
:
full_time_equivalent = models.DecimalField( max_digits=5, decimal_places=2, default=100, validators=[ MinValueValidator(Decimal(0)), MaxValueValidator(Decimal(100)) ] )
To make sure the validator fires, I override save
with the following command:
def save(self, *args, **kwargs): # Run validations self.full_clean() return super().save(*args, **kwargs)
Passed the following tests:
project2_membership = ProjectMembership( user=self.new_user, project=project2, is_project_manager=False, full_time_equivalent=10.01 )
When I enter validation, the following values and corresponding errors are displayed:
Decimal('10.0099999999999997868371792719699442386627197265625') django.core.exceptions.ValidationError: {'full_time_equivalent': ['Ensure that there are no more than 5 digits in total.']
What did I do wrong?
1> Alasdair..:
The decimal value 10.01
cannot be fully represented as a floating point number. When converting the value to a decimal number, you end up with Decimal('10.0099999999999997868371792719699442386627197265625')
, which is almost equal to Decimal('10.01')
, but max_digits
verification failed.
You can prevent the error by using the string '10.01'
or the decimal Decimal('10.01')
in your test.
from decimal import Decimal project2_membership = ProjectMembership( user=self.new_user, project=project2, is_project_manager=False, full_time_equivalent=Decimal('10.01') )