Python: how to create, submit, and handle a form using Flask

Python: how to create, submit, and handle a form using Flask

In this article, we will see how to create, submit, and handle a form using Flask.

Flask is a lightweight and flexible microframework for web development in Python. One of the fundamental features offered by Flask is the handling of forms submitted via the HTTP POST method. In this article, we will see how to create, submit, and handle a form using Flask.

Before starting, make sure you have Flask installed in your Python environment. You can install it using pip:


pip install Flask

Start by creating a simple Flask application. Create a folder for the project and within it, a file called app.py:


from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/submit', methods=['POST'])
def submit():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']
        # Add further processing or save the data to the database
        return f"Received: Name - {name}, Email - {email}"

if __name__ == '__main__':
    app.run(debug=True)

In the same directory, create a folder called templates and within it, a file index.html:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Submission</title>
</head>
<body>
    <form action="{{ url_for('submit') }}" method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

In summary:

  • Creating the Flask Application: The Flask application is created and configured in the app.py file.
  • Defining Routes: The index() function handles the base route (/) and renders the HTML template containing the form. The submit() function handles the /submit route and is called when the form is submitted.
  • Handling the POST Request: The submit() function checks if the request method is POST, extracts the data submitted from the form using request.form, and processes it (e.g., printing it or saving it to a database).

To start the application, run the app.py file:


python app.py

Open your browser and go to http://127.0.0.1:5000/ to view the form. Fill in the fields and submit the form to see the data processed by the server.

We can then add the following features:

  • Data Validation: It is important to validate the received data to ensure it is correct and safe. Flask-WTF is a library that can help with form validation.
  • Database Saving: You can extend the application to save the data in a database using SQLAlchemy or other database management libraries.
  • Error Handling: Implement appropriate error handling to manage any issues during form processing.

Here is an example of how to integrate Flask-WTF for form validation:


from flask import Flask, render_template, request, redirect, url_for, flash
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Email

app = Flask(__name__)
app.secret_key = 'supersecretkey'

class MyForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MyForm()
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data
        flash(f'Received: Name - {name}, Email - {email}')
        return redirect(url_for('index'))
    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)

In the index.html template, use Flask-WTF to generate the form:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form Submission</title>
</head>
<body>
    <form method="post" action="">
        {{ form.hidden_tag() }}
        <p>
            {{ form.name.label }}<br>
            {{ form.name(size=32) }}<br>
            {% for error in form.name.errors %}
                <span style="color: red;">[{{ error }}]</span><br>
            {% endfor %}
        </p>
        <p>
            {{ form.email.label }}<br>
            {{ form.email(size=32) }}<br>
            {% for error in form.email.errors %}
                <span style="color: red;">[{{ error }}]</span><br>
            {% endfor %}
        </p>
        <p>{{ form.submit() }}</p>
    </form>
    {% with messages = get_flashed_messages() %}
        {% if messages %}
            <ul>
                {% for message in messages %}
                    <li>{{ message }}</li>
                {% endfor %}
            </ul>
        {% endif %}
    {% endwith %}
</body>
</html>

Conclusion

Handling form submission via POST in Flask is relatively simple and can be enriched with validation and error handling using libraries like Flask-WTF. With this knowledge, you can develop more interactive and secure web applications.