Skip to main content

SplitArrayField

This class provides a form field that handles a fixed-size array of values by wrapping a base field and utilizing a specialized widget. It manages the validation and cleaning of individual array items, with support for removing trailing null values and reporting specific errors for invalid items. The field ensures that data is correctly transformed into a Python list while maintaining consistency with the base field's validation logic.

Attributes

AttributeTypeDescription
default_error_messagesdict = {"item_invalid": _("Item %(nth)s in the array did not validate:")}A dictionary containing the default error message templates used for validation failures, specifically for reporting invalid items within the array.

Constructor

Signature

def SplitArrayField(
base_field: forms.Field,
size: int,
remove_trailing_nulls: boolean = False,
**kwargs: dict
) - > null

Parameters

NameTypeDescription
base_fieldforms.FieldThe Django form field class to be used for each item in the array.
sizeintThe fixed number of items in the array.
remove_trailing_nullsboolean = FalseWhether to strip empty values from the end of the array during validation.
**kwargsdictAdditional keyword arguments passed to the parent Field class.

Methods


to_python()

@classmethod
def to_python(
value: list
) - > list

Converts the input list of values into Python objects by calling the base field's conversion logic on each item. This ensures each element in the array is cast to its appropriate Python data type.

Parameters

NameTypeDescription
valuelistThe raw input data received from the widget, typically a list of strings or primitive values.

Returns

TypeDescription
listA new list containing the converted Python objects for every item in the input array.

clean()

@classmethod
def clean(
value: list
) - > list

Validates the entire array by cleaning each individual item and handling trailing nulls. It aggregates validation errors from all sub-fields and raises a combined ValidationError if any items fail validation.

Parameters

NameTypeDescription
valuelistThe collection of data items to be validated and cleaned.

Returns

TypeDescription
listThe list of fully validated and cleaned data items, potentially truncated if trailing nulls were removed.

has_changed()

@classmethod
def has_changed(
initial: any,
data: list
) - > boolean

Determines if the field's value has changed from the initial data, accounting for trailing null removal. It converts the submitted data to Python objects before performing the comparison to ensure accuracy.

Parameters

NameTypeDescription
initialanyThe original value of the field used for comparison.
datalistThe new data submitted through the form to check for changes.

Returns

TypeDescription
booleanTrue if the submitted data differs from the initial value, False otherwise.