Home Backend Development Python Tutorial Flask-WTF: Adding a form to your Flask application

Flask-WTF: Adding a form to your Flask application

Jun 17, 2023 pm 09:50 PM
- flask - flask-wtf - form

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
Copy after login

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!'
Copy after login

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:

  • StringField: used to enter strings.
  • IntegerField: used to enter integers.
  • BooleanField: used to enter Boolean values ​​(checkboxes).
  • TextAreaField: used to enter multi-line text.
  • SelectField: used to select options in the drop-down menu.
  • RadioField: used for radio buttons.
  • FileField: used to upload files.

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')
Copy after login

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. DataRequiredThe 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')
Copy after login

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)
Copy after login

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>
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles