1import warnings
2from dataclasses import dataclass
3from dataclasses import field
4from dataclasses import replace
5from enum import StrEnum
6from itertools import groupby
7from operator import attrgetter
8from typing import NamedTuple
9
10from wtforms import widgets
11from wtforms._compat import get_signature
12from wtforms.fields.core import Field
13from wtforms.validators import ValidationError
14
15__all__ = (
16 "SelectField",
17 "Choice",
18 "SelectChoice",
19 "SelectMultipleField",
20 "RadioField",
21)
22
23
24class Choice(NamedTuple):
25 """
26 A rendered option yielded by
27 :meth:`SelectFieldBase.iter_choices` and
28 :meth:`SelectFieldBase.iter_groups`.
29
30 ``selected`` is computed against the field's current data. To
31 declare options on a :class:`SelectField`, use
32 :class:`SelectChoice` instead.
33
34 :param value:
35 The value that will be sent in the request.
36 :param label:
37 The label of the option.
38 :param selected:
39 Whether the option is currently selected. Set by ``iter_choices``;
40 you rarely set this yourself.
41 :param render_kw:
42 A dict containing HTML attributes that will be rendered
43 with the option.
44 """
45
46 value: str
47 label: str
48 selected: bool
49 render_kw: dict
50
51
52@dataclass
53class SelectChoice:
54 """
55 An option declared via :class:`SelectField` and
56 :class:`SelectMultipleField`'s ``choices=`` parameter.
57
58 :param value:
59 The value that will be sent in the request.
60 :param label:
61 The label of the option. Defaults to ``value`` when omitted.
62 :param render_kw:
63 A dict containing HTML attributes that will be rendered
64 with the option. Defaults to an empty dict when omitted.
65 :param optgroup:
66 The ``<optgroup>`` HTML tag in which the option will be rendered.
67 """
68
69 value: str
70 label: str = None # type: ignore[assignment]
71 render_kw: dict = field(default_factory=dict)
72 optgroup: str | None = None
73
74 def __post_init__(self):
75 if self.label is None:
76 self.label = self.value
77
78 def __iter__(self):
79 return iter((self.value, self.label, self.render_kw, self.optgroup))
80
81 @classmethod
82 def from_input(cls, input, optgroup=None):
83 """Coerce a value passed by the user via ``choices=...`` into a
84 :class:`SelectChoice`.
85 """
86 if isinstance(input, SelectChoice):
87 if optgroup:
88 return replace(input, optgroup=optgroup)
89 return input
90
91 if isinstance(input, Choice):
92 warnings.warn(
93 "Passing Choice to a SelectField is deprecated; Choice is the "
94 "output type returned by iter_choices(). Use SelectChoice "
95 "instead. Support for Choice as input will be removed in "
96 "WTForms 4.0.",
97 DeprecationWarning,
98 stacklevel=4,
99 )
100 return cls(
101 value=input.value,
102 label=input.label,
103 render_kw=input.render_kw,
104 optgroup=optgroup,
105 )
106
107 if isinstance(input, str):
108 return cls(value=input, optgroup=optgroup)
109
110 if isinstance(input, tuple):
111 if len(input) not in (2, 3):
112 raise ValueError(
113 f"SelectField choice tuple must have 2 or 3 elements, "
114 f"got {len(input)}"
115 )
116 return cls(*input, optgroup=optgroup)
117
118
119def _has_custom_str(enum_cls):
120 """Tell whether the enum or one of its user bases defines ``__str__``."""
121 stdlib = [
122 cls.__str__
123 for cls in enum_cls.__mro__
124 if cls.__module__ in ("enum", "builtins")
125 ]
126 return enum_cls.__str__ not in stdlib
127
128
129def _invoke_choices_callable(cb, form, field):
130 """Call a ``choices`` callable with ``(form, field)``, or with no argument."""
131 try:
132 sig = get_signature(cb)
133 except (ValueError, TypeError):
134 return cb()
135 try:
136 sig.bind(form, field)
137 except TypeError:
138 return cb()
139 return cb(form, field)
140
141
142def _enum_options(enum_cls, by, label, factory):
143 if by not in ("value", "name"):
144 raise ValueError(f"by must be 'value' or 'name', got {by!r}")
145 if label is None:
146 use_str = issubclass(enum_cls, StrEnum) or _has_custom_str(enum_cls)
147 label = str if use_str else lambda m: m.name
148 return [factory(value=getattr(m, by), label=label(m)) for m in enum_cls]
149
150
151def enum_choices(enum_cls, *, by="value", label=None):
152 """Build a list of :class:`SelectChoice` from an :class:`enum.Enum` class.
153
154 ``by`` selects which member attribute becomes the HTML ``value=``:
155 ``"value"`` (the default) emits ``member.value``, ``"name"`` emits
156 ``member.name``. Use ``"name"`` for enums whose values are not good
157 transport identifiers (non-string, non-unique or non-serialisable).
158
159 The label defaults to ``str(member)`` when the Enum defines its own
160 ``__str__`` or is a :class:`enum.StrEnum`, otherwise to ``member.name``.
161 Pass ``label=`` (a callable taking a member) to override.
162
163 Pair with :func:`enum_coerce` using the same ``by`` to round-trip the
164 submitted string back into a member.
165 """
166 return _enum_options(enum_cls, by, label, SelectChoice)
167
168
169def enum_coerce(enum_cls, *, by="value"):
170 """Return a ``coerce`` callable mapping a submitted string back to an
171 :class:`enum.Enum` member.
172
173 ``by`` must match the one passed to :func:`enum_choices`: ``"value"``
174 (the default) resolves ``str(member.value)`` — so ``IntEnum`` values
175 round-trip too — and ``"name"`` resolves ``member.name``. Already-coerced
176 members pass through unchanged.
177 """
178 if by not in ("value", "name"):
179 raise ValueError(f"by must be 'value' or 'name', got {by!r}")
180
181 def coerce(v):
182 if isinstance(v, enum_cls):
183 return v
184
185 try:
186 if by == "value":
187 by_value = {str(m.value): m for m in enum_cls}
188 return by_value[str(v)]
189 else:
190 return enum_cls[v]
191 except KeyError as e:
192 raise ValueError(str(e)) from e
193
194 return coerce
195
196
197def _normalize_iter_choice(choice):
198 """Coerce a value yielded by :meth:`SelectFieldBase.iter_choices` or
199 :meth:`SelectFieldBase.iter_groups` into a :class:`Choice`.
200 """
201 if isinstance(choice, Choice):
202 return choice
203 if isinstance(choice, tuple):
204 warnings.warn(
205 "Yielding raw tuples from iter_choices() or iter_groups() is "
206 "deprecated; yield Choice instances instead. Will be removed "
207 "in WTForms 4.0.",
208 DeprecationWarning,
209 stacklevel=3,
210 )
211 if len(choice) == 4:
212 value, label, selected, render_kw = choice
213 elif len(choice) == 3:
214 value, label, selected = choice
215 render_kw = {}
216 else:
217 raise TypeError(
218 f"iter_choices()/iter_groups() yielded a tuple of unsupported "
219 f"length: {len(choice)}"
220 )
221 return Choice(value=value, label=label, selected=selected, render_kw=render_kw)
222 raise TypeError(
223 f"iter_choices()/iter_groups() yielded an unsupported type: "
224 f"{type(choice).__name__}"
225 )
226
227
228class SelectFieldBase(Field):
229 option_widget = widgets.Option()
230
231 """
232 Base class for fields which can be iterated to produce options.
233
234 This isn't a field, but an abstract base class for fields which want to
235 provide this functionality.
236 """
237
238 def __init__(self, label=None, validators=None, option_widget=None, **kwargs):
239 super().__init__(label, validators, **kwargs)
240
241 if option_widget is not None:
242 self.option_widget = option_widget
243
244 def iter_choices(self):
245 """Provide data for choice widget rendering.
246
247 Should yield :class:`Choice` instances.
248 """
249 raise NotImplementedError()
250
251 def _iter_choices_normalized(self):
252 """Wrap :meth:`iter_choices` to always yield :class:`Choice`."""
253 for choice in self.iter_choices():
254 yield _normalize_iter_choice(choice)
255
256 def has_groups(self):
257 """Whether the field's choices include any ``optgroup`` hint."""
258 return False
259
260 def iter_groups(self):
261 """Yield ``(group_label, [Choice, ...])`` pairs for grouped rendering."""
262 raise NotImplementedError()
263
264 def _iter_groups_normalized(self):
265 """Wrap :meth:`iter_groups` to always yield ``(name, [Choice, ...])``."""
266 for name, group in self.iter_groups():
267 yield name, [_normalize_iter_choice(c) for c in group]
268
269 def __iter__(self):
270 opts = dict(
271 widget=self.option_widget,
272 validators=self.validators,
273 name=self.name,
274 render_kw=self.render_kw,
275 _form=self._form,
276 _meta=self.meta,
277 )
278 for i, choice in enumerate(self._iter_choices_normalized()):
279 opt = self._Option(
280 id=f"{self.id}-{i}",
281 label=choice.label or choice.value,
282 **opts,
283 )
284 opt.choice = choice
285 opt.checked = choice.selected
286 opt.process(None, choice.value)
287 yield opt
288
289 def _choices_from_input(self, choices):
290 """Parse the user-supplied ``choices`` into a list of :class:`SelectChoice`."""
291 if callable(choices):
292 warnings.warn(
293 "Passing a callable to _choices_from_input() is deprecated; "
294 "resolve the callable before the call. Will be removed in "
295 "WTForms 3.4.",
296 DeprecationWarning,
297 stacklevel=2,
298 )
299 choices = self._invoke_choices_callback(choices)
300
301 if choices is None:
302 return None
303
304 if isinstance(choices, dict):
305 if self._is_shorthand_dict(choices):
306 result = []
307 for key, value in choices.items():
308 if isinstance(value, dict):
309 for inner_value, inner_label in value.items():
310 result.append(
311 SelectChoice(
312 value=inner_value, label=inner_label, optgroup=key
313 )
314 )
315 else:
316 result.append(SelectChoice(value=key, label=value))
317 return result
318 return [
319 SelectChoice.from_input(input, optgroup)
320 for optgroup, inputs in choices.items()
321 for input in inputs
322 ]
323
324 return [SelectChoice.from_input(input) for input in choices]
325
326 @staticmethod
327 def _is_shorthand_dict(choices):
328 """``True`` if ``choices`` matches the shorthand dict syntax.
329
330 Shorthand is ``dict[str, str | dict[str, str]]``.
331 """
332 return all(isinstance(v, (str, dict)) for v in choices.values())
333
334 @staticmethod
335 def _warn_legacy_choices(choices):
336 """Emit a one-shot ``DeprecationWarning`` for legacy ``choices`` shapes.
337
338 Legacy shapes are raw tuples or ``dict``.
339 """
340 if isinstance(choices, dict):
341 if SelectFieldBase._is_shorthand_dict(choices):
342 return
343 warnings.warn(
344 "Passing SelectField choices in a dict is deprecated and will be "
345 "removed in wtforms 3.4. Please pass a list of SelectChoice "
346 "objects with a custom optgroup attribute instead.",
347 DeprecationWarning,
348 stacklevel=3,
349 )
350 items = (i for v in choices.values() for i in v)
351 else:
352 items = choices
353 for item in items:
354 if isinstance(item, (SelectChoice, Choice)):
355 continue
356 if isinstance(item, tuple):
357 warnings.warn(
358 "Passing SelectField choices as tuples is deprecated and "
359 "will be removed in wtforms 3.4. Please use SelectChoice "
360 "instead.",
361 DeprecationWarning,
362 stacklevel=3,
363 )
364 return
365
366 def _invoke_choices_callback(self, cb):
367 return _invoke_choices_callable(cb, self._form, self)
368
369 class _Option(Field):
370 def _value(self):
371 return str(self.data)
372
373
374class SelectField(SelectFieldBase):
375 widget = widgets.Select()
376
377 def __init__(
378 self,
379 label=None,
380 validators=None,
381 coerce=str,
382 choices=None,
383 validate_choice=True,
384 invalid_value_message=None,
385 invalid_choice_message=None,
386 **kwargs,
387 ):
388 super().__init__(label, validators, **kwargs)
389 self.coerce = coerce
390 if callable(choices):
391 self._choices_callable = choices
392 self._choices_stale = True
393 self._choices = None
394 else:
395 self._choices_callable = None
396 self._choices_stale = False
397 if choices is None:
398 self._choices = None
399 else:
400 self._warn_legacy_choices(choices)
401 self._choices = (
402 dict(choices) if isinstance(choices, dict) else list(choices)
403 )
404 self.validate_choice = validate_choice
405 self.invalid_value_message = invalid_value_message
406 self.invalid_choice_message = invalid_choice_message
407
408 @property
409 def choices(self):
410 """The field's choices, resolved from the callable on first read."""
411 if self._choices_stale:
412 self._choices_stale = False
413 self._choices = self._invoke_choices_callback(self._choices_callable)
414 return self._choices
415
416 @choices.setter
417 def choices(self, value):
418 if callable(value):
419 self._choices_callable = value
420 self._choices_stale = True
421 self._choices = None
422 else:
423 self._choices_callable = None
424 self._choices_stale = False
425 self._choices = value
426
427 def iter_choices(self):
428 choices = self._choices_from_input(self.choices) or []
429 return [
430 Choice(
431 value=c.value,
432 label=c.label,
433 selected=self.coerce(c.value) == self.data,
434 render_kw=c.render_kw,
435 )
436 for c in choices
437 ]
438
439 def has_groups(self):
440 choices = self._choices_from_input(self.choices) or []
441 return any(c.optgroup is not None for c in choices)
442
443 def iter_groups(self):
444 choices = self._choices_from_input(self.choices) or []
445 for optgroup, group in groupby(choices, key=attrgetter("optgroup")):
446 yield (
447 optgroup,
448 [
449 Choice(
450 value=c.value,
451 label=c.label,
452 selected=self.coerce(c.value) == self.data,
453 render_kw=c.render_kw,
454 )
455 for c in group
456 ],
457 )
458
459 def post_process(self, formdata=None):
460 super().post_process(formdata)
461 if self._choices_callable is not None:
462 self._choices_stale = True
463
464 def process_data(self, value):
465 try:
466 # If value is None, don't coerce to a value
467 self.data = self.coerce(value) if value is not None else None
468 except (ValueError, TypeError):
469 self.data = None
470
471 def process_formdata(self, valuelist):
472 if not valuelist:
473 return
474
475 try:
476 self.data = self.coerce(valuelist[0])
477 except (ValueError, TypeError) as exc:
478 raise ValueError(
479 self.invalid_value_message
480 or self.gettext("Invalid Choice: could not coerce.")
481 ) from exc
482
483 def pre_validate(self, form):
484 if self.process_errors:
485 return
486
487 if not self.validate_choice:
488 return
489
490 if self.choices is None:
491 raise TypeError(self.gettext("Choices cannot be None."))
492
493 if not any(choice.selected for choice in self._iter_choices_normalized()):
494 raise ValidationError(
495 self.invalid_choice_message or self.gettext("Not a valid choice.")
496 )
497
498
499class SelectMultipleField(SelectField):
500 """
501 No different from a normal select field, except this one can take (and
502 validate) multiple choices. You'll need to specify the HTML
503 :mdn-attr:`size` attribute on the :mdn-tag:`select` field when rendering.
504
505 ``invalid_choice_message`` may be a string, or a callable taking the
506 number of invalid submitted values and returning the message. The
507 returned message must contain ``%(value)s``, which is replaced with the
508 comma-separated list of unacceptable values.
509 """
510
511 widget = widgets.Select(multiple=True)
512
513 def __init__(
514 self,
515 label=None,
516 validators=None,
517 coerce=str,
518 choices=None,
519 validate_choice=True,
520 invalid_value_message=None,
521 invalid_choice_message=None,
522 **kwargs,
523 ):
524 super().__init__(
525 label,
526 validators,
527 coerce=coerce,
528 choices=choices,
529 validate_choice=validate_choice,
530 **kwargs,
531 )
532 self.invalid_value_message = invalid_value_message
533 self.invalid_choice_message = invalid_choice_message
534
535 def iter_choices(self):
536 choices = self._choices_from_input(self.choices) or []
537 data = self.data or ()
538 return [
539 Choice(
540 value=c.value,
541 label=c.label,
542 selected=self.coerce(c.value) in data,
543 render_kw=c.render_kw,
544 )
545 for c in choices
546 ]
547
548 def iter_groups(self):
549 choices = self._choices_from_input(self.choices) or []
550 data = self.data or ()
551 for optgroup, group in groupby(choices, key=attrgetter("optgroup")):
552 yield (
553 optgroup,
554 [
555 Choice(
556 value=c.value,
557 label=c.label,
558 selected=self.coerce(c.value) in data,
559 render_kw=c.render_kw,
560 )
561 for c in group
562 ],
563 )
564
565 def process_data(self, value):
566 try:
567 self.data = list(self.coerce(v) for v in value)
568 except (ValueError, TypeError):
569 self.data = None
570
571 def process_formdata(self, valuelist):
572 try:
573 self.data = list(self.coerce(x) for x in valuelist)
574 except (ValueError, TypeError) as exc:
575 raise ValueError(
576 self.invalid_value_message
577 or self.gettext(
578 "Invalid choice(s): one or more data inputs could not be coerced."
579 )
580 ) from exc
581
582 def pre_validate(self, form):
583 if self.process_errors:
584 return
585
586 if not self.validate_choice or not self.data:
587 return
588
589 if self.choices is None:
590 raise TypeError(self.gettext("Choices cannot be None."))
591
592 acceptable = {
593 self.coerce(choice.value) for choice in self._iter_choices_normalized()
594 }
595 if any(data not in acceptable for data in self.data):
596 unacceptable = [
597 str(data) for data in set(self.data) if data not in acceptable
598 ]
599 if callable(self.invalid_choice_message):
600 message = self.invalid_choice_message(len(unacceptable))
601 elif self.invalid_choice_message is not None:
602 message = self.invalid_choice_message
603 else:
604 message = self.ngettext(
605 "'%(value)s' is not a valid choice for this field.",
606 "'%(value)s' are not valid choices for this field.",
607 len(unacceptable),
608 )
609 raise ValidationError(message % dict(value="', '".join(unacceptable)))
610
611
612class RadioField(SelectField):
613 """
614 Like a SelectField, except displays a list of :mdn-input:`radio` buttons.
615
616 Iterating the field will produce subfields (each containing a label as
617 well) in order to allow custom rendering of the individual radio fields.
618 """
619
620 widget = widgets.ListWidget(prefix_label=False)
621 option_widget = widgets.RadioInput()
622
623 def __init__(self, label=None, validators=None, **kwargs):
624 super().__init__(label, validators, **kwargs)
625 self.label.field_id = False