Flask Report Part 5: Working with Flask Forms

Posted by

Flask Report Part 5: Flask Forms

Flask Report Part 5: Flask Forms

Forms are an essential part of web development as they allow users to interact with a website by entering data. In Flask, creating forms is made easy with the help of the Flask-WTF extension.

Setting Up a Form

To create a form in Flask, you first need to install the Flask-WTF extension. You can do this by running the following command:

pip install Flask-WTF

After installing the extension, you can create a form by defining a new Python class that inherits from flask_wtf.FlaskForm. Here’s an example of a simple form that allows users to enter their name:


    from flask_wtf import FlaskForm
    from wtforms import StringField, SubmitField

    class NameForm(FlaskForm):
        name = StringField('Name')
        submit = SubmitField('Submit')
  

Displaying the Form

To display the form in a template, you can use the {{ form. }} syntax. Here’s an example of how you can display the form created above:


    <form method="POST" action="">
        {{ form.hidden_tag() }}
        {{ form.name.label }} {{ form.name }}
        {{ form.submit }}
    </form>
  

Processing Form Data

To process the data submitted by the form, you can use the form.validate_on_submit() method in your Flask view function. Here’s an example of how you can process the form data:


    @app.route('/')
    def index():
        form = NameForm()
        if form.validate_on_submit():
            name = form.name.data
            return f'Hello, {name}!'
        return render_template('index.html', form=form)
  

And there you have it! With Flask-WTF, creating and processing forms in Flask is a breeze. If you’re looking to add interactive features to your Flask application, be sure to give Flask Forms a try!