Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Form Handling — Flask-WTF

Form Handling — Flask-WTF

In this chapter you will learn to handle forms in a standardized way with Flask-WTF: defining form classes, automatic CSRF protection, field validation, and error messages.


Why Use Flask-WTF?

The registration and login forms in the previous chapter were handwritten: manually getting values from request.form.get() , manually validating, and manually displaying errors.

Flask-WTF wraps WTForms for Flask, providing:


Installation and Configuration



(venv) $ pip install flask-wtf

Configure SECRET_KEY in app.py (CSRF Token depends on this key):

Example

File path: app.py

app.

config

[

'SECRET_KEY'

]

=

'your-secret-key'

   

Use an environment variable in production

app.

config

[

'WTF_CSRF_ENABLED'

]

=

True

           

Enabled by default; declare it explicitly


Define Form Classes

Example

File path: app/forms.py (new file)

from

flask_wtf

import

FlaskForm

from

wtforms

import

StringField

,

PasswordField

,

EmailField

,

BooleanField

from

wtforms.

validators

import

DataRequired

,

Length

,

Email

,

EqualTo

,

ValidationError

from

app.

models

import

User

class

RegisterForm

(

FlaskForm

)

:

   

"""Registration Form"""

    username

=

StringField

(

'Username'

,

validators

=

[

        DataRequired

(

message

=

'Username cannot be empty'

)

,

        Length

(

min

=

3

,

max

=

50

,

message

=

'Username must be 3-50 characters long'

)

   

]

)

   

email

=

EmailField

(

'Email'

,

validators

=

[

        DataRequired

(

message

=

'Email cannot be empty'

)

,

        Email

(

message

=

'Please enter a valid email address'

)

   

]

)

    password

=

PasswordField

(

'Password'

,

validators

=

[

        DataRequired

(

message

=

'Password cannot be empty'

)

,

        Length

(

min

=

6

,

message

=

'Password must be at least 6 characters'

)

   

]

)

    confirm_password

=

PasswordField

(

'Confirm Password'

,

validators

=

[

        DataRequired

(

message

=

'Please enter the password again'

)

,

        EqualTo

(

'password'

,

message

=

'The two passwords do not match'

)

   

]

)

   

Custom validator: check whether the username is already registered

   

def

validate_username

(

self

,

field

)

:

       

if

User.

query

.

filter_by

(

username

=

field.

data

)

.

first

(

)

:

           

raise

ValidationError

(

'This username is already taken.'

)

   

def

validate_email

(

self

,

field

)

:

       

if

User.

query

.

filter_by

(

email

=

field.

data

)

.

first

(

)

:

           

raise

ValidationError

(

'This email is already registered.'

)

class

LoginForm

(

FlaskForm

)

:

   

"""Login Form"""

    username

=

StringField

(

'Username'

,

validators

=

[

        DataRequired

(

message

=

'Username cannot be empty'

)

   

]

)

    password

=

PasswordField

(

'Password'

,

validators

=

[

        DataRequired

(

message

=

'Password cannot be empty'

)

   

]

)

    remember

=

BooleanField

(

'Remember me'

)

Common Field Types

Field Class HTML tag Description
StringField Single-line text
PasswordField Password input
EmailField Email input
TextAreaField

        {{ form.submit(class="btn-submit") }}

   

   

        Already have an account?

Login now

   

{% endblock %}

Flask-WTF's CSRF protection is automatic:form.hidden_tag() It generates a hidden containing a random Token; the server verifies this Token before accepting a POST request. Any form submitted from an external site is rejected because it does not have the correct Token.


Manual request.form vs Flask-WTF Comparison

Aspect Manual request.form Flask-WTF
Lines of code Repeat get/validate/report three steps for every field Form class defined once
CSRF protection Must be implemented manually automatically
Custom validation Manual if/else validate_xxx method
Error display Manual concatenation form.field.errors collected automatically
Applicable scenarios Simple forms (e.g., search box) Complex forms (registration, login, profile editing)

Chapter Summary

In this chapter you refactored the auth forms with Flask-WTF: FlaskForm defines fields and validators, validate_xxx provides custom validation, form.validate_on_submit() handles POST validation uniformly, form.hidden_tag() provides automatic CSRF protection, and error messages are rendered in templates.

Form handling is now more standardized and secure.