Skip to main content

IntegerField

This class provides a form field for handling integer input, ensuring that values can be converted to whole numbers. It supports validation for minimum and maximum values, as well as step size constraints, and automatically updates widget attributes to reflect these limits. The class also handles localization and sanitization of numeric strings during the conversion process.

Attributes

AttributeTypeDescription
widget[Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = NumberInputThe default widget class used to render this field in HTML forms, typically a NumberInput.
default_error_messagesdict = {"invalid": _("Enter a whole number.")}A dictionary containing the default error message for invalid whole number inputs.
re_decimalregex pattern = _lazy_re_compile(r".0*\s*$")A compiled regular expression used to identify and strip trailing decimal points and zeros from numeric strings during validation.

Constructor

Signature

def IntegerField(
max_value: int = None,
min_value: int = None,
step_size: int = None,
**kwargs: dict
) - > null

Parameters

NameTypeDescription
max_valueint = NoneThe maximum allowed value for the field.
min_valueint = NoneThe minimum allowed value for the field.
step_sizeint = NoneThe amount by which the value must be incremented or decremented.
**kwargsdictAdditional keyword arguments passed to the parent Field class.

Methods


to_python()

@classmethod
def to_python(
value: any
) - > int

Validate that int() can be called on the input. Return the result of int() or None for empty values.

Parameters

NameTypeDescription
valueanyThe raw input value to be converted into an integer, which may include localized separators or trailing decimal zeros.

Returns

TypeDescription
intThe integer representation of the input value, or None if the input is empty.

widget_attrs()

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

Updates the HTML attributes for the associated widget to include numeric constraints like min, max, and step.

Parameters

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

Returns

TypeDescription
dictA dictionary of HTML attributes to be applied to the widget, including 'min', 'max', and 'step' if defined.