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
| Attribute | Type | Description |
|---|---|---|
| widget | [Widget](../widgets/widget.md?sid=django_forms_widgets_widget) = Select | The form widget class used to render the field in HTML, defaulting to Select. |
| default_error_messages | dict = {"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
| Name | Type | Description |
|---|---|---|
| choices | `tuple | list` = () |
| **kwargs | dict | Additional 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
| Type | Description |
|---|---|
list | The 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
| Name | Type | Description |
|---|---|---|
| value | iterable | An 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
| Name | Type | Description |
|---|---|---|
| value | any | The raw input value to be converted into a Python-friendly string format. |
Returns
| Type | Description |
|---|---|
str | The 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
| Name | Type | Description |
|---|---|---|
| value | any | The 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
| Name | Type | Description |
|---|---|---|
| value | any | The value to search for within the defined choices, supporting both direct and string-based comparisons. |
Returns
| Type | Description |
|---|---|
bool | True if the value matches any key in the choices list or within nested optgroups, False otherwise. |