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.
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.
Before we dive into forms, let's set up a basic Flask application.
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.
Now, let's create a form. In Flask, forms are created using the Flask-WTF extension. First, install the extension using pip:
pip install flask-wtfNext, create a new file called forms.py and add the following code:
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.
Now, let's modify the home.html file to render the form:
<!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.
To handle form submissions, let's modify the Flask application to process the form data:
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.
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.
Which Flask extension is used to create and manage forms?