Skip to main content

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

AttributeTypeDescription
hidden_widgetclass = MultipleHiddenInputThe widget class used to render the field when it is hidden, defaulting to MultipleHiddenInput.
widgetclass = SelectMultipleThe default widget class used to render the field in HTML, defaulting to SelectMultiple.
default_error_messagesdict = {"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

NameTypeDescription
valueanyThe raw input value from the form submission to be converted

Returns

TypeDescription
listA 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

NameTypeDescription
valuelistThe list of selected values to validate against the available field choices

Returns

TypeDescription
nullNone

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

NameTypeDescription
initiallistThe original values assigned to the field
datalistThe new values submitted via the form

Returns

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