Skip to content

SelectMultipleField pre_validate expects a tuple list even though a normal list is a valid argument #612

@d3-f4ult

Description

@d3-f4ult

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugUnexpected behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions