@@ -775,10 +775,8 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=
775
775
776
776
def to_internal_value (self , data ):
777
777
"""
778
- Validates that the input is a decimal number. Returns a Decimal
779
- instance. Returns None for empty values. Ensures that there are no more
780
- than max_digits in the number, and no more than decimal_places digits
781
- after the decimal point.
778
+ Validate that the input is a decimal number and return a Decimal
779
+ instance.
782
780
"""
783
781
data = smart_text (data ).strip ()
784
782
if len (data ) > self .MAX_STRING_LENGTH :
@@ -798,6 +796,16 @@ def to_internal_value(self, data):
798
796
if value in (decimal .Decimal ('Inf' ), decimal .Decimal ('-Inf' )):
799
797
self .fail ('invalid' )
800
798
799
+ return self .validate_precision (value )
800
+
801
+ def validate_precision (self , value ):
802
+ """
803
+ Ensure that there are no more than max_digits in the number, and no
804
+ more than decimal_places digits after the decimal point.
805
+
806
+ Override this method to disable the precision validation for input
807
+ values or to enhance it in any way you need to.
808
+ """
801
809
sign , digittuple , exponent = value .as_tuple ()
802
810
decimals = exponent * decimal .Decimal (- 1 ) if exponent < 0 else 0
803
811
@@ -824,16 +832,22 @@ def to_representation(self, value):
824
832
if not isinstance (value , decimal .Decimal ):
825
833
value = decimal .Decimal (six .text_type (value ).strip ())
826
834
827
- context = decimal .getcontext ().copy ()
828
- context .prec = self .max_digits
829
- quantized = value .quantize (
830
- decimal .Decimal ('.1' ) ** self .decimal_places ,
831
- context = context
832
- )
835
+ quantized = self .quantize (value )
836
+
833
837
if not self .coerce_to_string :
834
838
return quantized
835
839
return '{0:f}' .format (quantized )
836
840
841
+ def quantize (self , value ):
842
+ """
843
+ Quantize the decimal value to the configured precision.
844
+ """
845
+ context = decimal .getcontext ().copy ()
846
+ context .prec = self .max_digits
847
+ return value .quantize (
848
+ decimal .Decimal ('.1' ) ** self .decimal_places ,
849
+ context = context )
850
+
837
851
838
852
# Date & time fields...
839
853
0 commit comments