Flask Forms Tutorial 🎯

beginner
19 min

Flask Forms Tutorial 🎯

Welcome to our comprehensive guide on Flask Forms! In this lesson, we'll learn how to create and render forms in Flask applications. By the end of this tutorial, you'll be able to create interactive web pages that accept user input.

What are Flask Forms? 📝

Flask Forms are a convenient way to handle user input in a Flask application. They simplify the process of validating and processing user-submitted data, making it easier to build robust and secure web applications.

Setting Up a Basic Flask App 🎯

Before we dive into forms, let's set up a basic Flask application.

python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('home.html') if __name__ == '__main__': app.run(debug=True)

In this example, we've created a simple Flask application with a single route (/) that renders a template named home.html.

Creating a Form 🎯

Now, let's create a form. In Flask, forms are created using the Flask-WTF extension. First, install the extension using pip:

bash
pip install flask-wtf

Next, create a new file called forms.py and add the following code:

python
from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import DataRequired class NameForm(FlaskForm): name = StringField('What is your name?', validators=[DataRequired()]) submit = SubmitField('Submit')

In this example, we've created a form called NameForm with a name field and a submit button. The DataRequired validator ensures that the user must provide a name before submitting the form.

Rendering the Form 🎯

Now, let's modify the home.html file to render the form:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Flask Forms</title> </head> <body> <h1>Hello, World!</h1> <form method="post" action=""> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name }} {{ form.submit() }} </form> </body> </html>

In this example, we've used Jinja templates to render the form. The hidden_tag() function generates a hidden input that contains a CSRF token for security purposes.

Handling Form Submissions 🎯

To handle form submissions, let's modify the Flask application to process the form data:

python
from flask import Flask, render_template, request from forms import NameForm app = Flask(__name__) app.config['SECRET_KEY'] = 'your-secret-key' @app.route('/', methods=['GET', 'POST']) def home(): form = NameForm() if form.validate_on_submit(): print(f'Hello, {form.name.data}!') return render_template('success.html') return render_template('home.html', form=form) if __name__ == '__main__': app.run(debug=True)

In this example, we've added the validate_on_submit() method to check if the form is valid. If the form is valid, we print a greeting message and redirect to a success page. If the form is not valid, we render the home page with the form pre-populated.

Conclusion 🎯

You've now learned the basics of creating and rendering forms in a Flask application. In the next lesson, we'll explore advanced topics such as form validation and error handling.

Quick Quiz
Question 1 of 1

Which Flask extension is used to create and manage forms?