Reputation: 1
I'm trying to create a form with two Submit Fields - Filter and Submit. For Filter, I have a Select Field with a list of names, and if they select a name I want to filter the existing page based on that name. For Submit, I have a Radio Field and want to jump to a different page based on the selection. For Filter, I don't want any validation of the Radio Field, and for Submit I don't want any validation of the Select Field.
This appears to work fine with my Select Field - it only validates when I hit the Filter button. But for the Radio Field, it always validates and I get the following regardless of which button I click:
[Not a valid choice]
Here are my code snippets. Html:
<h2>Filter</h2>
<p>
{{ form.player.label }}<br>
{{ form.player }}
{% for error in form.player.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.filter() }}</p>
<h2>Games to be played</h2>
<p>
{{ form.result.label }}<br>
{{ form.result }}
{% for error in form.result.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>{{ form.submit() }}</p>
Form:
class MatchupsForm(FlaskForm):
player = SelectField(u'Filter by Player', coerce=int)
filter = SubmitField('Filter')
result = RadioField(u'Select Game to Update', coerce=int)
submit = SubmitField('Update')
def validate_player(self, player):
if (player.data == 0) and self.filter.data:
raise ValidationError("Please select a Name to filter on")
return False
return True
def validate_result(self, result):
if not result.data and self.submit.data:
raise ValidationError("Please select a Matchup")
return False
return True
I've tried the suggestion from Flask-WTForms How to override pre validate on Radio Fields by creating
def pre_validate(self, form):
for v, _ in self.choices:
if self.data == v:
break
else:
raise ValueError(self.gettext('Need a Matchup'))
But that didn't work either - I get the same error. Note that my additional validators seem to work correctly - when I click Filter with no player selection, I see that error, but if I click Submit with no result selection, I see both the default error and my customized one.
[Not a valid choice] [Please select a Matchup]
Appreciate any insights on how to make this work.
Upvotes: 0
Views: 482
Reputation: 1
Try to manually create an hidden field with the same name as your RadioField and give it a value you can manually validate when the form submit.
Upvotes: 0