Welcome to our comprehensive guide on setting up Flask-WTF, a powerful and easy-to-use combination of Flask andWTForms for building web applications. By the end of this tutorial, you'll be well-versed in creating forms, handling user input, and validating data in your Flask projects. Let's dive right in!
Flask-WTF is an extension for Flask that simplifies the process of creating and handling web forms in Flask applications. It integrates WTForms, a popular and robust library for creating dynamic and user-friendly web forms in Python, into Flask projects.
To install Flask-WTF, use the following command in your terminal:
pip install flask-wtfLet's create a simple contact form for our application. First, import the necessary modules and create a Form class.
from flask import Flask
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, validators
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'
class ContactForm(FlaskForm):
name = StringField('Name', validators=[validators.DataRequired()])
email = StringField('Email', validators=[validators.DataRequired(), validators.Email()])
message = StringField('Message', validators=[validators.DataRequired()])
submit = SubmitField('Submit')š” Pro Tip: Always use the SECRET_KEY configuration when running a Flask application to enhance security.
Now, let's create a route to render our form and handle the form submission.
@app.route('/contact', methods=['GET', 'POST'])
def contact():
form = ContactForm()
if form.validate_on_submit():
# Handle form submission here
return 'Form submitted successfully!'
return render_template('contact.html', form=form)In the example above, we create a route for /contact that displays the form if the request method is GET and handles the form submission if it's POST. The form data is validated using the validate_on_submit() method.
Question: What is the primary purpose of the validate_on_submit() method?
A: It renders the form
B: It validates the form data
C: It handles form submission
Correct: B
Explanation: The validate_on_submit() method is used to validate the form data in Flask-WTF applications.
Next, let's create a contact.html file in our templates folder (app/templates) to display our form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
<form method="POST" novalidate>
{{ form.csrf_token }}
{{ form.name.label }}<br>
{{ form.name }}<br>
{{ form.email.label }}<br>
{{ form.email }}<br>
{{ form.message.label }}<br>
{{ form.message }}<br>
{{ form.submit }}
</form>
</body>
</html>In this template, we loop through the form fields and display them using their labels and input tags.
Finally, let's run our application to see the contact form in action.
app.run(debug=True)That's it! You've successfully set up Flask-WTF and created a simple contact form. Now, you can extend this example to create more complex forms, validate user input, and process form submissions in your Flask applications. Happy coding! š