Dynamic choices WTForms Flask SelectField

The main idea here is to assign the choices list to the field after instantiation. To do so you need to use argument coerce=int. The coerce keyword arg to SelectField says that we use int() to coerce form data. The default coerce is unicode(). Correct FormModel: class AddName(FlaskForm): name =StringField(‘Device name’, validators=[InputRequired(),Length(min=4, max=30)]) groupID = … Read more

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

Multiple forms in a single page using flask and WTForms

The solution above have a validation bug, when one form cause a validation error, both forms display an error message. I change the order of if to solve this problem. First, define your multiple SubmitField with different names, like this: class Form1(Form): name = StringField(‘name’) submit1 = SubmitField(‘submit’) class Form2(Form): name = StringField(‘name’) submit2 = … Read more