WTF (WTForms) - Web Forms with Flask
Syntax
from wtforms import Form, StringField, IntegerField, validators
class MyForm(Form):
name = StringField('Name', [validators.DataRequired()])
age = IntegerField('Age', [validators.DataRequired(), validators.NumberRange(min=18)])
Example
from flask import Flask, render_template, request
from wtforms import Form, StringField, TextAreaField, validators
app = Flask(__name__)
class ContactForm(Form):
name = StringField("Name", [validators.DataRequired()])
email = StringField("Email", [validators.DataRequired(), validators.Email()])
subject = StringField("Subject", [validators.DataRequired()])
message = TextAreaField("Message", [validators.DataRequired()])
@app.route("/contact", methods=["GET", "POST"])
def contact():
form = ContactForm(request.form)
if request.method == "POST" and form.validate():
print(form.name.data)
print(form.email.data)
print(form.subject.data)
print(form.message.data)
return render_template("contact.html", form=form)
Output
The output will be a form with four fields: Name, Email, Subject, and Message. Upon submitting the form, it will print the data entered in the console.
Explanation
WTForms is a Python package that allows you to define web forms in Python classes. It provides a simple way to define forms, validate user input, and render the form HTML.
In the given example, the ContactForm class is defined with four fields: name, email, subject, and message. Each field has one or more validators to ensure that the user enters valid data. When the user submits the form, it is validated using the form.validate() method. If the data is valid, the form data is printed to the console.
Use
WTForms is commonly used in Flask web applications to define and validate web forms. It is a simple and powerful package that streamlines the process of handling user input.
Important Points
- WTForms is a Python package used to define and validate web forms.
- It is commonly used in Flask web applications.
- Fields are defined as class attributes with one or more validators.
- The form can be validated using the form.validate() method.
Summary
WTForms is a powerful Python package that simplifies the process of defining and validating web forms. It provides a straightforward way to handle user input and is commonly used in Flask web applications.