📅  最后修改于: 2023-12-03 14:41:13.631000             🧑  作者: Mango
Flask-WTF is an extension for Flask that integrates WTForms library, a flexible forms validation and rendering library for Python web development, to make it easy to create and validate forms with Flask.
Here's how to install Flask-WTF using Shell/Bash commands:
$ pip install flask-wtf
This will install Flask-WTF and its dependencies.
Make sure you have Flask installed on your system before installing Flask-WTF. If you don't have Flask installed, you can install it using the following command:
$ pip install flask
Once Flask-WTF is installed, you can import it into your Flask application and start using it to create and validate forms.
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class MyForm(FlaskForm):
name = StringField('Name', validators=[DataRequired()])
submit = SubmitField('Submit')
In this example, we create a new form called MyForm
that has a single field called name
and a submit button. The DataRequired
validator ensures that the name
field is not empty when the form is submitted.
To render this form in a Flask view, we can do something like this:
from flask import render_template
@app.route('/form', methods=['GET', 'POST'])
def form():
form = MyForm()
if form.validate_on_submit():
# Do something with form data
return 'Submitted'
return render_template('form.html', form=form)
In this example, we create a new view called /form
that renders a template called form.html
and passes the MyForm
instance to the template. We also check if the form is submitted and valid using form.validate_on_submit()
, and if so, we can do something with the form data and return a success message.
That's it! Flask-WTF makes it easy to create and validate forms in Flask.