Introduction to Flask-WTF
Flask-WTF is an extension of Flask that simplifies form handling and validation using WTForms. This tutorial will guide you through installing Flask-WTF, creating and handling forms, and implementing validation and error handling with real examples.
Step 1: Installing Flask-WTF
To use Flask-WTF, you need to install it along with Flask. Use the following command:
pip install flask flask-wtf
Once installed, you can import the necessary classes and functions in your Flask application.
Step 2: Creating and Handling Forms
Create a Python file, for example, app.py. Start by importing the required modules:
from flask import Flask, render_template, redirect, url_for from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key'
Define a form class by extending FlaskForm:
class NameForm(FlaskForm): name = StringField('Enter your name:', validators=[DataRequired()]) submit = SubmitField('Submit')
Next, create a route to render the form and handle its submission:
@app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): name = form.name.data return redirect(url_for('greet', name=name)) return render_template('index.html', form=form) @app.route('/greet/') def greet(name): return f"Hello, {name}!"
In the templates directory, create an HTML file called index.html to render the form:
Flask-WTF Form Submit Your Name
Step 3: Validation and Error Handling
Flask-WTF makes validation easy with the help of WTForms validators. The DataRequired validator ensures that the name field is not left empty. Update your index.html template to display validation errors:
Flask-WTF Form Submit Your Name
When a user submits the form without entering a name, an error message will be displayed.
Step 4: Running the Application
Run your Flask application:
python app.py
Navigate to http://127.0.0.1:5000 to test the form. Enter a name and submit it to see the greeting page. If you submit without entering a name, an error message will appear.
Complete Example
Here is the complete app.py file:
from flask import Flask, render_template, redirect, url_for from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' class NameForm(FlaskForm): name = StringField('Enter your name:', validators=[DataRequired()]) submit = SubmitField('Submit') @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): name = form.name.data return redirect(url_for('greet', name=name)) return render_template('index.html', form=form) @app.route('/greet/') def greet(name): return f"Hello, {name}!" if __name__ == '__main__': app.run(debug=True)
Conclusion
In this tutorial, we explored Flask-WTF by installing the extension, creating and handling forms, and using validation and error handling. This approach simplifies form handling and improves user experience in Flask applications.