Blog Datasheets Home About me Clients My work Services Contact

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:

  1. Form Classes: Define your forms as classes, which allows for reusable form code and organization.
  2. Validation: Comes with built-in validators and also allows for custom validators.
  3. CSRF Protection: Provides Cross-Site Request Forgery (CSRF) protection out of the box.
  4. Integration with Flask: Seamlessly integrates with Flask, using Flask’s request and session handling.

Setting Up Flask-WTF

  1. Install Flask-WTF:

    1
    
    pip install Flask-WTF
    
  2. 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

  1. Define a Form Class: Forms are defined as classes, inheriting from FlaskForm. Each field is represented by a class variable, using WTForms field classes like StringField, 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')
    
  2. Rendering Forms in Templates: In your Jinja2 templates, you can render the form fields individually or render the entire form at once.

    1
    2
    3
    4
    5
    6
    
    <form method="post">
        {{ form.hidden_tag() }}
        {{ form.username.label }} {{ form.username() }}
        {{ form.password.label }} {{ form.password() }}
        {{ form.submit() }}
    </form>
    
  3. 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.

    1
    2
    3
    4
    5
    6
    7
    
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        form = LoginForm()
        if form.validate_on_submit():
            # Handle valid form submission
            return redirect(url_for('dashboard'))
        return render_template('login.html', form=form)
    

Advanced Form Handling

  1. Custom Validators: You can define custom validators to add specific validation logic for your fields.

  2. File Uploads: Flask-WTF makes it easier to handle file uploads with the FileField and file validators.

  3. Dynamic Forms: You can dynamically add fields to your forms based on certain conditions or user input.

  4. Multi-Page Forms: Handle multi-page or multi-step forms by preserving form data across requests, using sessions or hidden fields.

Best Practices

  1. CSRF Protection: Always include {{ form.hidden_tag() }} in your forms for CSRF protection.
  2. Validation Feedback: Provide user feedback for validation errors in your templates.
  3. Secure File Uploads: If handling file uploads, ensure to validate file types and handle storage securely.
  4. 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.


➡️ I2C Communication with AVR Atmega-328: A Step-by-Step Tutorial


⬅️ More about databases in Flask


Go back to Posts.