G2Labs Grzegorz Grzęda
Form handling in Flask
March 2, 2024
Form Handling in Flask is an important aspect for creating interactive and user-friendly web applications. Flask doesn’t include a form-handling component by default, but it can be efficiently handled using extensions like Flask-WTF, which integrates the WTForms package with Flask.
Flask-WTF for Form Handling
Flask-WTF is an extension for Flask that simplifies form creation, validation, and handling. It is built on top of WTForms, a flexible form rendering and validation library.
Key Features:
- Form Classes: Define your forms as classes, which allows for reusable form code and organization.
- Validation: Comes with built-in validators and also allows for custom validators.
- CSRF Protection: Provides Cross-Site Request Forgery (CSRF) protection out of the box.
- Integration with Flask: Seamlessly integrates with Flask, using Flask’s request and session handling.
Setting Up Flask-WTF
Install Flask-WTF:
1
pip install Flask-WTF
Configure Secret Key: Flask-WTF uses a secret key to protect forms against CSRF. Set the secret key in your Flask configuration.
1
app.config['SECRET_KEY'] = 'your-very-secret-key'
Creating Forms with Flask-WTF
Define a Form Class: Forms are defined as classes, inheriting from
FlaskForm
. Each field is represented by a class variable, using WTForms field classes likeStringField
,PasswordField
, etc.1 2 3 4 5 6 7 8
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Email, Length class LoginForm(FlaskForm): username = StringField('Username', validators=[InputRequired(), Length(min=4, max=15)]) password = PasswordField('Password', validators=[InputRequired(), Length(min=8, max=80)]) submit = SubmitField('Login')
Rendering Forms in Templates: In your Jinja2 templates, you can render the form fields individually or render the entire form at once.
Handling Form Submission: In your route, instantiate the form and handle the form submission. Use
form.validate_on_submit()
to check if the form is submitted and valid.
Advanced Form Handling
Custom Validators: You can define custom validators to add specific validation logic for your fields.
File Uploads: Flask-WTF makes it easier to handle file uploads with the
FileField
and file validators.Dynamic Forms: You can dynamically add fields to your forms based on certain conditions or user input.
Multi-Page Forms: Handle multi-page or multi-step forms by preserving form data across requests, using sessions or hidden fields.
Best Practices
- CSRF Protection: Always include
{{ form.hidden_tag() }}
in your forms for CSRF protection. - Validation Feedback: Provide user feedback for validation errors in your templates.
- Secure File Uploads: If handling file uploads, ensure to validate file types and handle storage securely.
- Form and Field Customization: Customize the form and field rendering to fit the style of your application.
Conclusion
Form handling is a critical component of web development, and Flask-WTF offers a powerful and flexible way to manage forms in Flask applications. It not only simplifies the creation and validation of forms but also integrates seamlessly with Flask’s paradigms, making the development of form-intensive applications more streamlined and secure.