Skip to main content

ChoiceField

This class represents a form field that allows users to select from a predefined set of options. It handles the normalization of choices, ensures the selected value is present within the allowed options (including nested optgroups), and synchronizes these choices with its associated selection widget.

Attributes

AttributeTypeDescription
widget[Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = SelectThe form widget class used to render the field in HTML, defaulting to Select.
default_error_messagesdict = {"invalid_choice": "Select a valid choice. %(value)s is not one of the available choices."}A dictionary containing the default error message for the 'invalid_choice' key, used when a submitted value is not found in the available choices.

Constructor

Signature

def ChoiceField(
choices: tuple|list = (),
**kwargs: dict
) - > null

Parameters

NameTypeDescription
choices`tuplelist` = ()
**kwargsdictAdditional keyword arguments passed to the parent Field class.

Methods


choices()

@classmethod
def choices() - > list

Retrieves the current list of valid options available for this field.

Returns

TypeDescription
listThe normalized list of choice tuples used for validation and widget rendering.

choices()

@classmethod
def choices(
value: iterable
)

Sets the available options for the field and automatically synchronizes them with the associated widget after normalization.

Parameters

NameTypeDescription
valueiterableAn iterable of choices or grouped choices to be normalized and assigned to the field and its widget.

to_python()

@classmethod
def to_python(
value: any
) - > str

Return a string.

Parameters

NameTypeDescription
valueanyThe raw input value to be converted into a Python-friendly string format.

Returns

TypeDescription
strThe value converted to a string, or an empty string if the input is considered an empty value.

validate()

@classmethod
def validate(
value: any
)

Validate that the input is in self.choices.

Parameters

NameTypeDescription
valueanyThe value to check against the allowed choices; raises a ValidationError if the value is invalid.

valid_value()

@classmethod
def valid_value(
value: any
) - > bool

Check to see if the provided value is a valid choice.

Parameters

NameTypeDescription
valueanyThe value to search for within the defined choices, supporting both direct and string-based comparisons.

Returns

TypeDescription
boolTrue if the value matches any key in the choices list or within nested optgroups, False otherwise.