Flask-WTF is a Python package designed to simplify Flask framework applications using forms. It provides a simple yet powerful interface to easily add forms to Flask applications. Using Flask-WTF, you can easily validate and process form data and add custom validators and fields to your forms. This article will introduce how to use Flask-WTF to add a form to a Flask application.
Install Flask-WTF
First, you need to install the Flask-WTF package. It can be installed using pip:
pip install Flask-WTF
Creating a Flask application
Before you start adding forms, you need to create a Flask application. Here is an example of a simple Flask application:
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!'
For more complex applications, more configuration and setup may be required.
Create form classes
Flask-WTF uses form classes to describe form fields. The form class is derived from the class FlaskForm
provided in Flask-WTF. In a form class, you can define form fields, validators, and other properties. The following are some basic form field types:
The following is a simple form class example:
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired class NameForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) submit = SubmitField('Submit')
In the above example, the form class NameForm
contains a file with the name name
string field and a submit button named submit
. String fields are defined using the StringField
type and the DataRequired
validator. DataRequired
The validator ensures that the field value is not empty.
In the form class, you can also define custom validators. For example, the following is a custom validator that ensures that the value entered by the user is less than 50 characters:
from wtforms import ValidationError class LengthValidator(object): def __init__(self, max_chars): self.max_chars = max_chars def __call__(self, form, field): if len(field.data) > self.max_chars: raise ValidationError('Value must be less than {} characters'.format(self.max_chars)) class NameForm(FlaskForm): name = StringField('Name', validators=[DataRequired(), LengthValidator(50)]) submit = SubmitField('Submit')
In the above example, a validator LengthValidator
is defined. The validator is initialized with a maximum length parameter and checks whether the length of the input field exceeds the maximum length. In the string field definition, add the LengthValidator
validator to the list of validators to ensure that its attribute value is under 50 characters.
In the form class, you can also define other properties, such as the CSS class used when rendering fields. These properties can be used to customize the look and feel of form fields.
Using Forms
To use a form in a Flask application, you need to create a form instance in the view function. A form instance can be created from the form class and passed to the template. The following is an example of a view function:
from flask import render_template from app import app from forms import NameForm @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): name = form.name.data return render_template('index.html', name=name) return render_template('index.html', form=form)
In the above example, the view function index
creates the form instance form
. If the form is submitted, and validation is successful, get the name from the submitted form and pass it to the template. Display the form if it has not been submitted or validation failed.
In the template, you can use the form rendering function provided by Flask-WTF to render the form. Here is a simple template example, using the Jinja2 template engine and Bootstrap styling:
<!doctype html> <html> <head> <title>Flask-WTF Example</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css"> </head> <body> <div class="container"> <h1>Hello {{ name }}!</h1> <form method="post"> {{ form.csrf_token }} {{ form.name.label }} {{ form.name }} {% for error in form.name.errors %} <span>{{ error }}</span> {% endfor %} {{ form.submit }} </form> </div> </body> </html>
In the template, use the form
object to render the form fields and submit button. The csrf_token
field is a hidden field used to prevent cross-site request forgery attacks.
Summary
Using Flask-WTF, you can easily add forms to your Flask application. Using form classes, you can create custom form fields and validators. In the view function, you can create a form instance and render the form using a template engine. Flask-WTF also provides other features such as file upload, form nesting and form preprocessing. Understanding the capabilities of Flask-WTF can make form processing in Flask applications simpler and more efficient.
The above is the detailed content of Flask-WTF: Adding a form to your Flask application. For more information, please follow other related articles on the PHP Chinese website!