Handle HTML forms with WTForms, validate input server-side, handle file uploads, and display flash messages.
pip install flask-wtfapp.config['SECRET_KEY'] = 'your-secret-key' # required for CSRFfrom flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, EmailField
from wtforms.validators import DataRequired, Email, Length
class ContactForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(min=2, max=50)])
email = EmailField('Email', validators=[DataRequired(), Email()])
message = TextAreaField('Message', validators=[DataRequired(), Length(min=10)])from .forms import ContactForm
from flask import flash
@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if form.validate_on_submit():
# form is valid and it was a POST
flash('Message sent!', 'success')
return redirect(url_for('index'))
return render_template('contact.html', form=form)form.hidden_tag() to your forms.form.validate_on_submit() returns True only on valid POST requests — the one method you need.flash('message', 'category') in the view, get_flashed_messages() in the template.