'WTForms RadioField preventing form validation
I have a WTForms form containing a few different types of fields, all of which work except the RadioField.
Python: from flask_wtf import FlaskForm from wtforms import validators, RadioField, DecimalField
class MyForm(FlaskForm):
field_one = DecimalField('Field 1', validators=[Optional()]
field_two = RadioField('Radio', choices=[(True, 'True'), (False, 'False')])
submit = SubmitField('Submit')
@app.route('/page', methods=['GET', 'POST'])
def page():
form = MyForm()
print('Page requested')
if form.validate_on_submit():
print('form validated')
return render_template('/page.html', form=form)
HTML:
<form method="POST">
<div class="row">
{{ form.hidden_tag() }}
{{ form.field_one.label }}
<div>
{{ form.field_one }}
</div>
</div>
<div class="row">
{{ form.hidden_tag() }}
{{ form.field_two.label }}
<div>
{% for subfield in form.field_two %}
<p>{{ subfield }} - {{ subfield.label }}
{% endfor %}
</div>
</div>
</form>
When I take out anything related to field_two (the RadioField), print('form validated') will execute every time I press submit.
But as soon as the RadioField is included the form is never validated. I thought it might be because the field doesn't have an associated validator, but it still doesn't work when I add validators=[Optional()] to the field_two definition.
Anyone know why the form isn't validated with the RadioField?
(I've tried the four options I can think of. Clicking submit with and without selecting a radio option, and adding and removing the Optional validator to the form definition.)
Solution 1:[1]
I had the same problem and found the working solution is to make a parent class that validates the RadioField class (see https://github.com/wtforms/wtforms/issues/477 for code). The failure of RadioFields to validate is a known issue.
Solution 2:[2]
To get around the validation issue of radio fields, adding validate_choice=False appears to have worked for me in the Form class:
radioChoice = RadioField("Example", choices=[("cpp", "C++"), ("py", "Python"), ("text", "Plain Text")], validate_choice=False)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JP Gerber |
| Solution 2 | Red Coleman |
