Flask Form Handling
In Flask, form handling is a common requirement when building web applications.
Handling form data involves receiving, validating, and processing forms submitted by users. Flask provides basic form handling capabilities, but is often combined with the Flask-WTF extension to simplify form operations and validation.
- Basic Form Handling: When using
request.formGet form data. - Using Flask-WTF: Combine with WTForms for form handling and validation, simplifying form operations.
- Form Validation: Use validators to ensure the validity of form data.
- File upload: Handle file uploads and saving files.
- CSRF protection: Protect forms against cross-site request forgery attacks.
1. Basic Form Handling
Flask provides a way to handle form data directly, using the request object to retrieve submitted data.
Create an HTML Form
Code in templates/form.html:
Example
Form Example
action="/submit": Form data is submitted to the /submit path.
method="post": Use the POST method to submit data.
Handle Form Data
Code in app.py:
Example
from
flask
import
Flask
,
render_template
,
request
app
=
Flask
(
name
)
@
app.
route
(
'/'
)
def
form
(
)
:
return
render_template
(
'form.html'
)
@
app.
route
(
'/submit'
,
methods
=
[
'POST'
]
)
def
submit
(
)
:
name
=
request.
form
.
get
(
'name'
)
=
request.
form
.
get
(
'email'
)
return
f
'Name: {name}, Email: {email}'
if
name
==
'main'
:
app.
run
(
debug
=
True
)
request.form.get('name') and request.form.get('email'): Retrieve the submitted form data.
2. Using the Flask-WTF Extension
Flask-WTF is an extension that wraps WTForms, providing form handling and validation features that make form handling more concise and powerful.
Install Flask-WTF
pip install flask-wtf
Configure Flask-WTF
Code in app.py:
Example
from
flask
import
Flask
,
render_template
,
redirect
,
url_for
from
flask_wtf
import
FlaskForm
from
wtforms
import
StringField
,
EmailField
,
SubmitField
from
wtforms.
validators
import
DataRequired
,
app
=
Flask
(
name
)
app.
secret_key
=
'your_secret_key'
Required for form protection
class
MyForm
(
FlaskForm
)
:
name
=
StringField
(
'Name'
,
validators
=
[
DataRequired
(
)
]
)
=
EmailField
(
'Email'
,
validators
=
[
DataRequired
(
)
,
(
)
]
)
submit
=
SubmitField
(
'Submit'
)
@
app.
route
(
'/'
,
methods
=
[
'GET'
,
'POST'
]
)
def
form
(
)
:
form
=
MyForm
(
)
if
form.
validate_on_submit
(
)
:
name
=
form.
name
.
data
=
form.
.
data
return
f
'Name: {name}, Email: {email}'
return
render_template
(
'form.html'
,
form
=
form
)
if
name
==
'main'
:
app.
run
(
debug
=
True
)
Create a Template to Support Flask-WTF Forms
Code in templates/form.html:
Example
Form Example
{{ form.hidden_tag() }}: Generates a hidden field to protect the form against CSRF attacks.
{{ form.name.label }} and {{ form.name(size=32) }}: Render the form field and its label.
3. Form Validation
Flask-WTF and WTForms provide rich form validation features. You can use built-in validators or custom validators to ensure the validity of form data.
Example
from
wtforms
import
Form
,
StringField
,
EmailField
,
SubmitField
from
wtforms.
validators
import
DataRequired
,
,
Length
class
MyForm
(
FlaskForm
)
:
name
=
StringField
(
'Name'
,
validators
=
[
DataRequired
(
)
,
Length
(
min
=
1
,
max
=
50
)
]
)
=
EmailField
(
'Email'
,
validators
=
[
DataRequired
(
)
,
(
)
]
)
submit
=
SubmitField
(
'Submit'
)
DataRequired(): Ensure a field is not empty.Length(min=1, max=50): Restrict the minimum and maximum length of a string.Email(): Validate whether a field is a valid email address.
4. File upload
Flask also supports handling file uploads. Uploaded files can be accessed via request.files.
Create a File Upload Form
Code in templates/upload.html:
Example
Upload File
enctype="multipart/form-data": Specifies the encoding type of the form data, supporting file uploads.
Handle File Uploads
Code in app.py:
Example
from
flask
import
Flask
,
request
,
redirect
,
url_for
app
=
Flask
(
name
)
app.
secret_key
=
'your_secret_key'
@
app.
route
(
'/upload'
,
methods
=
[
'POST'
]
)
def
upload
(
)
:
file
=
request.
files
.
get
(
'file'
)
if
file
:
filename
=
file
.
filename
file
.
save
(
f
'uploads/{filename}'
)
return
f
'File uploaded successfully: {filename}'
return
'No file uploaded'
if
name
==
'main'
:
app.
run
(
debug
=
True
)
request.files.get('file'): Retrieve the uploaded file object.
file.save(f'uploads/{filename}'): Save the file to the specified directory.
5. CSRF Protection
Flask-WTF automatically provides CSRF protection for forms. You need to configure a secret key to enable CSRF protection and include a hidden CSRF token in the template.
Configure CSRF Protection
app.secret_key = 'your_secret_key'
Add the CSRF token to the template: