Python > Web Development with Python > Flask > Forms

Flask Form Example: Simple Input Form

This snippet demonstrates a basic Flask application with a simple HTML form for user input. It covers defining a form class using `FlaskForm`, rendering the form in a template, and handling the form submission.

Form Definition (forms.py)

This code defines a form using `FlaskForm` from `flask_wtf`. `NameForm` has two fields: a `StringField` called `name` for text input, and a `SubmitField` to trigger form submission. The `DataRequired` validator ensures that the `name` field cannot be left blank.

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')

Flask Application (app.py)

This is the main Flask application. It initializes the Flask app, sets a secret key (crucial for security), defines the `index` route to handle form rendering and submission. `form.validate_on_submit()` checks if the form has been submitted and if all validators pass. If valid, it stores the submitted name in the session and redirects to the same page, effectively displaying the submitted name. The `render_template` function passes the form object and the name to the template.

from flask import Flask, render_template, session, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'  # Replace with a strong, random key

class NameForm(FlaskForm):
    name = StringField('What is your name?', validators=[DataRequired()])
    submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))

if __name__ == '__main__':
    app.run(debug=True)

HTML Template (templates/index.html)

This HTML template displays the form. `{{ form.csrf_token }}` is essential for CSRF protection. `{{ form.name.label }}` renders the label for the 'name' field, and `{{ form.name() }}` renders the input field itself. `{{ form.submit() }}` renders the submit button. The Jinja2 templating engine allows us to pass variables from the Flask app to the html and display the submitted name.

<!DOCTYPE html>
<html>
<head>
    <title>Flask Form Example</title>
</head>
<body>
    <h1>Flask Form Example</h1>
    {% if name %}
        <p>Hello, {{ name }}!</p>
    {% endif %}
    <form method="POST">
        {{ form.csrf_token }}
        {{ form.name.label }} {{ form.name() }}<br>
        {{ form.submit() }}
    </form>
</body>
</html>

Concepts Behind the Snippet

This example demonstrates the fundamental concepts of form handling in Flask: defining a form class, rendering the form in an HTML template, validating the form data, and processing the submitted data. Flask-WTF simplifies form creation and validation, while Jinja2 makes it easy to render forms dynamically.

Real-Life Use Case

This snippet could be used as the basis for a simple login form, a contact form, or any other form that requires user input. You can extend this example by adding more fields, validators, and logic to handle the submitted data in a more sophisticated way.

Best Practices

  • Always use a strong, random secret key for your Flask app.
  • Enable CSRF protection to prevent cross-site request forgery attacks.
  • Use validators to ensure that the user input is valid.
  • Sanitize user input to prevent cross-site scripting (XSS) attacks.

When to use them

Use forms when you need to collect data from users. This includes scenarios like registration, login, contact forms, surveys, and any situation where user input is required to perform an action.

Alternatives

Alternatives to Flask-WTF include using raw HTML forms and handling the validation and processing logic manually, or using other form libraries like WTForms directly without Flask-WTF's integration. However, Flask-WTF provides a convenient and secure way to handle forms in Flask applications.

Pros

  • Simplified form creation and validation.
  • Built-in CSRF protection.
  • Easy integration with Flask.
  • Clean and organized code.

Cons

  • Requires understanding of Flask-WTF and WTForms.
  • Can be overkill for very simple forms.

FAQ

  • What is CSRF protection?

    CSRF (Cross-Site Request Forgery) is a type of web security vulnerability where an attacker tricks a user into performing unwanted actions on a website they are logged into. CSRF protection adds a hidden token to forms to verify that the request is coming from the actual website and not a malicious source.
  • Why do I need a secret key?

    The secret key is used to encrypt session data and prevent tampering. It's crucial for security and should be a strong, random value.