Form is never valid with WTForms

Flask-WTF adds a CSRF protection field. If it’s not present, the CSRF validation will fail, and the form will be invalid. Use form.hidden_tag() to include any hidden fields in your form (including the CSRF field). <form method=”post”> {{ form.hidden_tag() }} … In general, if a form is not validating, you should check form.errors after calling … Read more

Determine which WTForms button was pressed in a Flask view

You added two buttons to the form, so check which of the fields’ data is True. from flask import Flask, render_template, redirect, url_for from flask_wtf import Form from wtforms import SubmitField app = Flask(__name__) app.secret_key = ‘davidism’ class StatsForm(Form): user_stats = SubmitField() room_stats = SubmitField() @app.route(‘/stats’, methods=[‘GET’, ‘POST’]) def stats(): form = StatsForm() if form.validate_on_submit(): … Read more

Flask-WTF – validate_on_submit() is never executed

You’re not inserting the CSRF field in the HTML form. <form method=post> {{ form.csrf_token }} {{ form.name }} <input type=submit> </form> After adding form.csrf_token to the template (docs), the form will validate as expected. Add print(form.errors) after validating the form to see the errors that were raised. errors will be empty before validation. In this … Read more

Add a css class to a field in wtform

You actually don’t need to go to the widget level to attach an HTML class attribute to the rendering of the field. You can simply specify it using the class_ parameter in the jinja template. e.g. {{ form.email(class_=”form-control”) }} will result in the following HTML:: <input class=”form-control” id=”email” name=”email” type=”text” value=””> to do this dynamically, … Read more