I am using the following code in a Flask-wtforms. I have tried with and without various validators in the SelectField but on the first time the user submits the form validation returns false.
I have also tried removing the extra validate method but still leaving a validator in the SelectField and again validation returns False on first submit.
Essentially I want to know if the SelectField is not set to a value of -1 (ie has been populated by the view method and presumably user is happy with the currently active item). I am not sure why the form if valid on second submit even though nothing else has been selected on the form
forms.py
something = SelectField(label = 'Something', choices = [('-1','Select Something')], default=('-1','Select Something'), id='select_something', validators=[validators.DataRequired(message='Nothing selected')])
#NB the line below with no validator also prints "--validate() returned false"
#something = SelectField(label = 'Something', choices = [('-1','Select Something')], default=('-1','Select Something'), id='select_something')
submit = SubmitField('Submit')
def validate(self):
rv = Form.validate(self)
if not rv:
print("--validate() returned false")
return False
#the line below never fired, see fix in following line
#if self.something.data == -1:
if str(self.something.data) == '-1':
logger.debug("--validate() data==-1")
return False
return True
view.py
form = Something(request.form)
if request.method == 'GET':
#get tuple_list from database
...
form.something.choices = tuple_list
form.something.default = tuple_list[0]
if request.method == 'POST' and form.validate():
print('Something added.')