1
votes

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.)

2

2 Answers

2
votes

I believe it is because of type checking. You should tell it to coerce to boolean like so:

field_two = RadioField('Radio', coerce=bool, choices=[(True, 'True'), (False, 'False')])

Edit: or even better, use 1 and 0 and coerce to int like so:

field_two = RadioField('Radio', coerce=int, choices=[(1, 'True'), (0, 'False')])

You can then check for value being truthy, or convert it too boolean like so:

bool(form.field_two.data)
0
votes

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.