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 pre_validate expects a tuple list even though a normal list is a valid argument #612

Closed
d3-f4ult opened this issue May 29, 2020 · 1 comment · Fixed by #661
Labels
bug Unexpected behavior

Comments

@d3-f4ult
Copy link

d3-f4ult commented May 29, 2020

Due to the patch provided in #605 SelectMultipleField.pre_validate() behaves unexpectedly, the method wasn't updated to support a value only list as choices.

pre_validate expects choices to be a list of (value, label) tuples thus validating the choices by doing:

values = list(c[0] for c in self.choices)
for d in self.data:
    if d not in values:
        raise ValidationError(
            self.gettext("'%(value)s' is not a valid choice for this field")
                % dict(value=d)
                )

however this means that if choices is a value only list, such as ['foo', 'bar'], c[0] in self.choices checks for the first char of the element (c[0]='f', c[0]='b') breaking the validation.

A possible fix could be reusing the checks used in iter_choices:

if not self.choices:
    choices = []
elif isinstance(self.choices[0], (list, tuple)):
    choices = self.choices
else:
    choices = zip(self.choices, self.choices)	

however I personally suggest that formatting choices at __init__ would be a better option, it would stop these issues and make things more consistent. The main issue is that at the moment every method that uses choices has to check for its format, might as well define it a the top and be done with it.

@azmeuk
Copy link
Member

azmeuk commented Oct 5, 2020

Could reproduce with:

>>> import wtforms
>>> class F(wtforms.Form):
...     foo = wtforms.SelectMultipleField(choices=["foo", "bar"])
>>> F(foo=["foo"]).validate()
False

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