Skip to content Skip to sidebar Skip to footer

Flask-WTForms How To Override Pre Validate On Radio Fields

I'm trying to raise an error when a user submits without selecting a radio choice and it's not working. When I render the fields like this: {{ render_field(form.example) }} it prin

Solution 1:

Try this script:

from flask import Flask
from flask import render_template
from flask import request
from flask import flash
from flask import redirect
from flask_wtf import FlaskForm
from wtforms import SelectField
from wtforms.widgets import ListWidget, RadioInput
from wtforms.validators import DataRequired


app = Flask(__name__)

class ReligionField(SelectField):
    widget = ListWidget(prefix_label=False)
    option_widget = RadioInput()

    def pre_validate(self, form):
        for v, _ in self.choices:
            if self.data == v:
                break
        else:
            raise ValueError(self.gettext('PICK SOMETHING'))

class ReligionForm(FlaskForm):
    religions = ['Christian', 'Muslim', 'Hindu', 'Buddhist']
    choices = [(x.lower(), x.title()) for x in sorted(religions)]
    religion = ReligionField('Religion', validators=[DataRequired()], choices=choices, render_kw={"class":"post", "type":"radio"})


@app.route('/',methods=['GET','POST'])
def hello_world():
    form = ReligionForm(request.form)

    if request.method == 'POST':
        if form.validate_on_submit():
        print form.religion.data
        else:
        print form.religion.errors[0]
        flash(form.religion.errors[0])
        return redirect('/')
    return render_template('radio.html', form=form)


if __name__ == "__main__":
    app.run()

radio.html

{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

<form method="post">
{% for subfield in form.religion %}
        <li>{{subfield.label}} {{subfield}} </li>
    {% endfor %}

<button>Submit</button>
</form>

Post a Comment for "Flask-WTForms How To Override Pre Validate On Radio Fields"