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
| Attribute | Type | Description |
|---|---|---|
| coerce | callable = lambda val: val | A callable used to convert the input value to a specific Python data type, which raises a ValidationError if the conversion fails. |
| empty_value | string = "" | 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
| Name | Type | Description |
|---|---|---|
| coerce | callable = lambda val: val | A function that takes a value and returns it coerced to a specific type. |
| empty_value | string = "" | The value to use to represent 'empty'. |
| **kwargs | dict | Additional 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
| Name | Type | Description |
|---|---|---|
| value | any | The raw data from the form submission to be validated and transformed |
Returns
| Type | Description |
|---|---|
any | The cleaned and type-coerced value ready for use in a validated data dictionary |