MultipleChoiceField
This class provides a form field that allows users to select one or more options from a predefined list of choices. It handles the normalization of input into a list of strings and validates that every selected value corresponds to a valid choice. The class uses specialized widgets for multiple selection and includes logic to detect changes between initial and submitted data sets.
Attributes
| Attribute | Type | Description |
|---|---|---|
| hidden_widget | class = MultipleHiddenInput | The widget class used to render the field when it is hidden, defaulting to MultipleHiddenInput. |
| widget | class = SelectMultiple | The default widget class used to render the field in HTML, defaulting to SelectMultiple. |
| default_error_messages | dict = {"invalid_choice": "Select a valid choice. %(value)s is not one of the available choices.", "invalid_list": "Enter a list of values." } | A dictionary containing the default error messages for invalid_choice and invalid_list validation errors. |
Methods
to_python()
@classmethod
def to_python(
value: any
) - > list
Normalizes the input value into a list of strings. Raises a ValidationError if the input is not a list or tuple.
Parameters
| Name | Type | Description |
|---|---|---|
| value | any | The raw input value from the form submission to be converted |
Returns
| Type | Description |
|---|---|
list | A list of strings representing the selected choices, or an empty list if no value is provided |
validate()
@classmethod
def validate(
value: list
) - > null
Validate that the input is a list or tuple.
Parameters
| Name | Type | Description |
|---|---|---|
| value | list | The list of selected values to validate against the available field choices |
Returns
| Type | Description |
|---|---|
null | None |
has_changed()
@classmethod
def has_changed(
initial: list,
data: list
) - > boolean
Determines if the field value has changed from the initial data. Compares the set of initial values against the submitted data, ignoring order and string type differences.
Parameters
| Name | Type | Description |
|---|---|---|
| initial | list | The original values assigned to the field |
| data | list | The new values submitted via the form |
Returns
| Type | Description |
|---|---|
boolean | True if the submitted data differs from the initial values, False otherwise |