Skip to content

Commit bee70e5

Browse files
committed
feat: dict choices shortcut for datalists
1 parent 62bbb07 commit bee70e5

4 files changed

Lines changed: 29 additions & 1 deletion

File tree

CHANGES.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
.. currentmodule:: wtforms
22

3+
Version 3.3.0b4
4+
---------------
5+
6+
Unreleased
7+
8+
- :class:`~datalist.DataList` ``choices`` accepts the shorthand
9+
``{value: label}`` dict syntax. :issue:`886`
10+
311
Version 3.3.0b3
412
---------------
513

docs/fields.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -610,7 +610,8 @@ Data Lists
610610

611611
``choices`` is either a list of :class:`~wtforms.DataListChoice`
612612
(or plain strings, in which case the string is used as both value
613-
and label), or a callable invoked at render time. The callable
613+
and label), a shorthand ``{value: label}`` dict, or a callable
614+
invoked at render time. The callable
614615
may take no argument (``fn()``) for a static list, or ``(field)``
615616
to adapt the suggestions to the current field value at each
616617
render — convenient for server-side filtering::

src/wtforms/datalist.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,10 @@ def iter_choices(self, field=None):
121121
raw = self._choices
122122
if raw is None:
123123
return []
124+
if isinstance(raw, dict):
125+
return [
126+
DataListChoice(value=value, label=label) for value, label in raw.items()
127+
]
124128
return [DataListChoice.from_input(item) for item in raw]
125129

126130
def __call__(self, field=None, **kwargs):

tests/test_datalist.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,21 @@ def test_choice_choices_render_value_and_label():
4848
assert 'label="United States"' in html
4949

5050

51+
def test_dict_shorthand_choices_render_value_and_label():
52+
"""A ``{value: label}`` dict renders both ``value=`` and ``label=`` attributes."""
53+
54+
class F(Form):
55+
country = StringField(
56+
datalist=DataList({"FR": "France", "US": "United States"})
57+
)
58+
59+
html = str(F().country.datalist())
60+
assert 'value="FR"' in html
61+
assert 'label="France"' in html
62+
assert 'value="US"' in html
63+
assert 'label="United States"' in html
64+
65+
5166
@pytest.mark.parametrize(
5267
("postdata", "expected"),
5368
[

0 commit comments

Comments
 (0)