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

Flask Form Handling

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.

  1. Basic Form Handling: When using request.form Get form data.
  2. Using Flask-WTF: Combine with WTForms for form handling and validation, simplifying form operations.
  3. Form Validation: Use validators to ensure the validity of form data.
  4. File upload: Handle file uploads and saving files.
  5. 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

   

<p>Form Example</p>

   

       

       

       


       

       

       


       

   

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'

)

   

email

=

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

,

Email

app

=

Flask

(

name

)

app.

secret_key

=

'your_secret_key'

 

Required for form protection

class

MyForm

(

FlaskForm

)

:

    name

=

StringField

(

'Name'

,

validators

=

[

DataRequired

(

)

]

)

   

email

=

EmailField

(

'Email'

,

validators

=

[

DataRequired

(

)

,

Email

(

)

]

)

    submit

=

SubmitField

(

'Submit'

)

@

app.

route

(

'/'

,

methods

=

[

'GET'

,

'POST'

]

)

def

form

(

)

:

    form

=

MyForm

(

)

   

if

form.

validate_on_submit

(

)

:

        name

=

form.

name

.

data

       

email

=

form.

email

.

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

   

<p>Form Example</p>

   

        {{ form.hidden_tag() }}

       

            {{ form.name.label }}


            {{ form.name(size=32) }}

       

       

            {{ form.email.label }}


            {{ form.email(size=32) }}

       

       

            {{ form.submit() }}

       

   

{{ 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

,

Email

,

Length

class

MyForm

(

FlaskForm

)

:

    name

=

StringField

(

'Name'

,

validators

=

[

        DataRequired

(

)

,

Length

(

min

=

1

,

max

=

50

)

   

]

)

   

email

=

EmailField

(

'Email'

,

validators

=

[

        DataRequired

(

)

,

Email

(

)

   

]

)

    submit

=

SubmitField

(

'Submit'

)

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

   

<p>Upload File</p>

   

       

       

       


       

   

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:

Example

    {{ form.hidden_tag() }}