Skip to main content

DecimalField

This class handles the validation and normalization of decimal input into Python Decimal instances. It supports constraints for maximum digits and decimal places, ensuring that values are finite and conform to specified precision limits. Additionally, it provides localized number parsing and automatically configures widget attributes for numeric input steps.

Attributes

AttributeTypeDescription
default_error_messagesdict = {"invalid": _("Enter a number.")}A dictionary of error message keys and their corresponding translated strings used for validation failures.

Constructor

Signature

def DecimalField(
max_value: Any = None,
min_value: Any = None,
max_digits: int = None,
decimal_places: int = None,
**kwargs: dict
)

Parameters

NameTypeDescription
max_valueAny = NoneThe maximum allowed value for the field.
min_valueAny = NoneThe minimum allowed value for the field.
max_digitsint = NoneThe maximum number of digits allowed in the number.
decimal_placesint = NoneThe maximum number of decimal places allowed.
**kwargsdictAdditional keyword arguments passed to the parent IntegerField class.

Methods


to_python()

@classmethod
def to_python(
value: Any
) - > Decimal | None

Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point.

Parameters

NameTypeDescription
valueAnyThe raw input value to be converted into a Decimal object.

Returns

TypeDescription
`DecimalNone`

validate()

@classmethod
def validate(
value: Decimal
) - > None

Validates that the input value is a finite number and not NaN or infinity.

Parameters

NameTypeDescription
valueDecimalThe Decimal instance to check for finiteness.

Returns

TypeDescription
NoneReturns nothing but raises a ValidationError if the value is not a finite number.

widget_attrs()

@classmethod
def widget_attrs(
widget: [Widget](../widgets/widget.md?sid=django_forms_widgets_widget)
) - > dict

Updates the HTML attributes for the associated form widget, specifically setting the 'step' attribute based on decimal_places.

Parameters

NameTypeDescription
widget[Widget](../widgets/widget.md?sid=django_forms_widgets_widget)The form widget instance for which attributes are being generated.

Returns

TypeDescription
dictA dictionary of HTML attributes to be applied to the form widget.