Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SelectMultipleField should support choices specified as coercible values. #822

Closed
andycaine opened this issue Dec 29, 2023 · 2 comments · Fixed by #823
Closed

SelectMultipleField should support choices specified as coercible values. #822

andycaine opened this issue Dec 29, 2023 · 2 comments · Fixed by #823
Labels
bug Unexpected behavior

Comments

@andycaine
Copy link
Contributor

Actual Behavior

>>> class DummyPostData(dict):
...     def getlist(self, key):
...             v = self[key]
...             if not isinstance(v, (list, tuple)):
...                     v = [v]
...             return v
...
>>> import wtforms
>>> class F(wtforms.Form):
...     foo=wtforms.SelectMultipleField(choices=[('1', 'One'), ('2', 'Two')], coerce=int)
...
>>> post_data = DummyPostData(foo=["1", "2"])
>>> form = F(post_data)
>>> form.validate()
False
>>> form.errors
{'foo': ["'1', '2' are not valid choices for this field."]}

Expected Behavior

The form should be valid when the post data is a valid option after coercing both post data and choices:

>>> class DummyPostData(dict):
...     def getlist(self, key):
...             v = self[key]
...             if not isinstance(v, (list, tuple)):
...                     v = [v]
...             return v
...
>>> import wtforms
>>> class F(wtforms.Form):
...     foo=wtforms.SelectMultipleField(choices=[('1', 'One'), ('2', 'Two')], coerce=int)
...
>>> post_data = DummyPostData(foo=["1", "2"])
>>> form = F(post_data)
>>> form.validate()
True

Environment

  • Python version: 3.9
  • wtforms version: 3.1.1
@azmeuk
Copy link
Member

azmeuk commented Dec 29, 2023

There is indeed a difference of behavior between SelectField and SelectMultipleField.

>>> import wtforms
>>> from werkzeug.datastructures import ImmutableMultiDict
>>> class F(wtforms.Form):
...     foo=wtforms.SelectMultipleField(choices=[('1', 'One'), ('2', 'Two')], coerce=int)
...     bar=wtforms.SelectField(choices=[('1', 'One'), ('2', 'Two')], coerce=int)
>>> form = F(ImmutableMultiDict({"foo": ["1"], "bar": ["1"]}))
>>> form.validate()
False
>>> form.errors
{'foo': ["'1' is not a valid choice for this field."]}

@azmeuk
Copy link
Member

azmeuk commented Jan 6, 2024

Fixed in version 3.1.2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Unexpected behavior
Development

Successfully merging a pull request may close this issue.

2 participants