Working with Forms and User Input

Share:

When building a web application, handling user input is one of the most vital tasks. With Flask, a popular Python-based micro-web framework, understanding and working with forms and user inputs is quite straightforward. In this tutorial, we are going to explore how to work with forms and handle user inputs using Flask.

We will set up a basic Flask application that receives input from the user through a form and then processes it. We will be using the Flask-WTF extension, which is a Flask wrapper around the WTForms module. Before we begin, we need to install the necessary packages, which are Flask and Flask-WTF.

pip install flask flask-wtf

Let's start by creating a simple Flask application. Let's use the scenario of a movie review web page where visitors can submit their reviews. Create a new Flask app as follows:

from flask import [Flask](https://stackbay.org/modules/learn-flask)
app = [Flask](https://stackbay.org/modules/learn-flask)(__name__)

@app.route('/')
def home():
    return 'Welcome to Movie Reviews App!'

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

Now, to work with forms, we first create a form class that describes the form fields to be rendered on the webpage. For our movie review application, the form class would look like this:

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import DataRequired

class ReviewForm(FlaskForm):
    username = StringField('Your Name', validators=[DataRequired()])
    title = StringField('Movie Title', validators=[DataRequired()])
    review = TextAreaField('Your Review', validators=[DataRequired()])
    submit = SubmitField('Submit')

In above code, we have three form fields: username, title, and review. Each field is assigned a label that will appear alongside the field in the form, and validators enforce the input rules. The DataRequired validator ensures that a field is not submitted empty.

Now, let's create a route /review to handle the GET and POST requests. The GET request will render the form on the webpage and the POST request will process the received form data.

from flask import render_template, request
from .forms import ReviewForm

@app.route('/review', methods=['GET', 'POST'])
def review():
    form = ReviewForm()
    if form.validate_on_submit():
        username = form.username.data
        title = form.title.data
        review = form.review.data
        
        # You can process the data here
        print("Username: ", username)
        print("Movie Title: ", title)
        print("Review: ", review)

        # Clear form fields
        form.username.data = ''
        form.title.data = ''
        form.review.data = ''

    return render_template('review.html', form=form)

The if form.validate_on_submit(): part checks if the form data is valid when the form is submitted. If valid, it then collects the form data and processes it. In this case, it simply prints out the form data and then clears the form fields.

Now we need to create a template file to display the form. Flask uses the Jinja2 template engine, and the template files are typically stored in a templates folder in the same directory as your app. Let's create a file called review.html in a folder named templates and present the form.

<!DOCTYPE html>
<html>
<body>
    <h1>Movie Review</h1>
    <form method="POST">
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=30) }}
        </p>
        <p>
            {{ form.title.label }}<br>
            {{ form.title(size=30) }}
        </p>
        <p>
            {{ form.review.label }}<br>
            {{ form.review(cols=30, rows=5) }}
        </p>
        <p>
            {{ form.submit() }}
        </p>
    </form>
</body>
</html>

This template will display a form with three fields plus a submit button which are passed from our route through form=form. The hidden_tag is a CSRF token that Flask-WTF creates automatically for security purposes.

That's it! We now have a very simple Flask application where a user can submit their movie reviews. This article demonstrated the very basic of working with forms and user inputs in Flask, yet there's a lot more to explore. Future enhancements could include validation feedback, file uploads, handling multiple forms, working with Flask-Bootstrap for simpler form handling and presentation, and of course connecting to a database to store user-submitted data.

Flask provides a simple, flexible way to gather and handle user data via forms, with wide suite of tools and libraries at your disposal. This simplicity and flexibility is a hallmark of Flask, allowing developers to create robust and interactive web applications. Hopefully this tutorial has given you a good grounding in the basics and you're now confident enough to dive in and explore further!

0 Comment


Sign up or Log in to leave a comment


Recent job openings