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
| Attribute | Type | Description |
|---|---|---|
| default_error_messages | dict = {"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
| Name | Type | Description |
|---|---|---|
| max_value | Any = None | The maximum allowed value for the field. |
| min_value | Any = None | The minimum allowed value for the field. |
| max_digits | int = None | The maximum number of digits allowed in the number. |
| decimal_places | int = None | The maximum number of decimal places allowed. |
| **kwargs | dict | Additional 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
| Name | Type | Description |
|---|---|---|
| value | Any | The raw input value to be converted into a Decimal object. |
Returns
| Type | Description |
|---|---|
| `Decimal | None` |
validate()
@classmethod
def validate(
value: Decimal
) - > None
Validates that the input value is a finite number and not NaN or infinity.
Parameters
| Name | Type | Description |
|---|---|---|
| value | Decimal | The Decimal instance to check for finiteness. |
Returns
| Type | Description |
|---|---|
None | Returns 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
| Name | Type | Description |
|---|---|---|
| widget | [Widget](../widgets/widget.md?sid=django_forms_widgets_widget) | The form widget instance for which attributes are being generated. |
Returns
| Type | Description |
|---|---|
dict | A dictionary of HTML attributes to be applied to the form widget. |