wtforms-sqlalchemy icon indicating copy to clipboard operation
wtforms-sqlalchemy copied to clipboard

`QuerySelectMultipleField` validation doesn't behave as expected on non-existing values

Open lvs-csis opened this issue 5 years ago • 0 comments

We've found that QuerySelectMultipleField sometimes has funny validation behaviour. When choosing a non-existing value and validating, we get that form.validate() returns True, but then validating again it returns False. The problem seems to be in pre_validate that _invalid_formdata is not updated if _get_data is not called. So a fix to this would be:

    def pre_validate(self, form):
        data = self.data
        if self._invalid_formdata:
            raise ValidationError(self.gettext('Not a valid choice'))
        elif data:
            obj_list = list(x[1] for x in self._get_object_list())
            for v in self.data:
                if v not in obj_list:
                    raise ValidationError(self.gettext('Not a valid choice')) 

And a test (in QuerySelectMultipleFieldTest) that now fails, but would pass with the fix:

    def test_validate_nonexisting_value(self):
        form = self.F(DummyPostData(a=['3']))
        form.a.query = self.sess.query(self.Test)
        self.assertFalse(form.validate())

lvs-csis avatar Aug 27 '18 10:08 lvs-csis