Flask Form Handling

In Flask, form handling is a common requirement when building web applications.

Handling form data involves receiving, validating, and processing user-submitted forms. Flask provides basic form handling capabilities, but it is usually combined with the Flask-WTF extension to simplify form operations and validation.

  1. Basic form handling: Userequest.formGet form data.
  2. Use Flask-WTF: Combine WTForms for form handling and validation to simplify form operations.
  3. Form validation: Use validators to ensure the validity of form data.
  4. File upload: Handle file uploads and save files.
  5. CSRF protection: Ensure forms are protected against Cross-Site Request Forgery attacks.

1. Basic Form Handling

Flask provides a direct way to handle form data, using the request object to retrieve submitted data.

Create HTML Form

templates/form.html file code:

Example

<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <form action="/submit" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        <br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email">
        <br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

action="../submit": Form data is submitted to the /submit path.

method="post": Use the POST method to submit data.

Processing form data

app.py file code:

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')andrequest.form.get('email'): Get the submitted form data.

2. Use the Flask-WTF Extension

Flask-WTF is an extension that wraps WTForms, providing form handling and validation functionality, making form processing more concise and powerful.

Install Flask-WTF

pip install flask-wtf
Configure Flask-WTF

app.py file code:

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 templates to support Flask-WTF forms.

templates/form.html file code:

Example

<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>
    <form method="post">
        {{ form.hidden_tag() }}
        <div>
            {{ form.name.label }}<br>
            {{ form.name(size=32) }}
        </div>
        <div>
            {{ form.email.label }}<br>
            {{ form.email(size=32) }}
        </div>
        <div>
            {{ form.submit() }}
        </div>
    </form>
</body>
</html>

{{ form.hidden_tag() }}: Generate a hidden field to protect the form from CSRF attacks.

{{ form.name.label }}and{{ form.name(size=32) }}: Render form fields and their labels.

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')
  • DataRequired(): Ensure the field is not empty.
  • Length(min=1, max=50): Limit the minimum and maximum length of a string.
  • Email(): Verify whether the field is a valid email address.

4. File upload

Flask also supports file upload handling. Uploaded files can be retrieved viarequest.filesVisit.

Create File Upload Form

templates/upload.html file code:

Example

<!DOCTYPE html>
<html>
<head>
    <title>Upload File</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <label for="file">File:</label>
        <input type="file" id="file" name="file">
        <br>
        <input type="submit" value="Upload">
    </form>
</body>
</html>

enctype="multipart/form-data": Specify the encoding type of form data to support file uploads.

Handling file uploads

app.py file code:

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'): Get 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 in the template:

Example

<form method="post">
    {{ form.hidden_tag() }}
    <!-- Form fields here -->
</form>
other extensions