Skip to main content

TypedChoiceField

This class extends ChoiceField to provide automatic type conversion and validation for selected values. It uses a custom coercion function to transform input data into a specific type and handles the normalization of empty values. This ensures that the cleaned data conforms to the expected data type before further processing.

Attributes

AttributeTypeDescription
coercecallable = lambda val: valA callable used to convert the input value to a specific Python data type, which raises a ValidationError if the conversion fails.
empty_valuestring = ""The specific value used to represent an empty selection, which bypasses the coercion logic when encountered during validation.

Constructor

Signature

def TypedChoiceField(
coerce: callable = lambda val: val,
empty_value: string = "",
**kwargs: dict
)

Parameters

NameTypeDescription
coercecallable = lambda val: valA function that takes a value and returns it coerced to a specific type.
empty_valuestring = ""The value to use to represent 'empty'.
**kwargsdictAdditional keyword arguments passed to the parent ChoiceField class.

Methods


clean()

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

Validates the input value against choice constraints and then coerces it into the final Python type.

Parameters

NameTypeDescription
valueanyThe raw data from the form submission to be validated and transformed

Returns

TypeDescription
anyThe cleaned and type-coerced value ready for use in a validated data dictionary