Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable the wtforms SelectField choices validation?

I have a wtforms form

class MyForm(Form):
    names = SelectField('name', choices=[])

The choices of names field is built dynamically and rendered in the template by an ajax call. When I submit the form, it raises an exception "not a valid choice". I don't want the form to validate the choices of names field for me. How can I disable the validation?

like image 225
shoujs Avatar asked Jan 21 '13 06:01

shoujs


2 Answers

I was stuck with the same issue. The solution provided by Xealot is great. I found that there is an option to set validation to False using validate_choice=False. I have included an example of both the solutions below.

class NonValidatingSelectField(SelectField):
    """
    Attempt to make an open ended select multiple field that can accept dynamic
    choices added by the browser.
    """
    def pre_validate(self, form):
        pass

class MyForm(Form):
    names = NonValidatingSelectField('name')
    names2 = SelectField('name2', validate_choice=False)
like image 117
Shantanu Avatar answered Nov 06 '22 17:11

Shantanu


I did something like this to step around the SelectMultipleField validation in WTForms. It should work the same way with a plain SelectField

class NonValidatingSelectMultipleField(SelectMultipleField):
    """
    Attempt to make an open ended select multiple field that can accept dynamic
    choices added by the browser.
    """
    def pre_validate(self, form):
        pass

I simply override the built-in validation.

like image 38
Xealot Avatar answered Nov 06 '22 16:11

Xealot