Forms and User Input in Flask
Key Concepts
- HTML Forms
- Handling Form Data
- Form Validation
- Redirects and Messages
HTML Forms
HTML forms are used to collect user input. They consist of various input elements like text fields, checkboxes, radio buttons, and submit buttons. Forms are defined using the <form>
tag and include attributes like action
and method
to specify where and how the form data should be sent.
<form action="/submit" method="post"> <label for="name">Name:</label> <input type="text" id="name" name="name"> <br> <label for="email">Email:</label> <input type="email" id="email" name="email"> <br> <input type="submit" value="Submit"> </form>
Handling Form Data
In Flask, form data is handled using the request
object. The request.form
attribute provides a dictionary-like interface to access the form data submitted via POST requests. This allows you to process and use the user input in your application.
from flask import Flask, request app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): name = request.form['name'] email = request.form['email'] return f"Received data: Name - {name}, Email - {email}" if __name__ == '__main__': app.run()
Form Validation
Form validation ensures that the user input meets certain criteria before it is processed. Flask provides various methods to validate form data, such as checking for required fields, validating email formats, and ensuring data length constraints. Validation helps maintain data integrity and security.
from flask import Flask, request, render_template app = Flask(__name__) @app.route('/submit', methods=['GET', 'POST']) def submit(): if request.method == 'POST': name = request.form['name'] email = request.form['email'] if not name or not email: return "Error: Both name and email are required." return f"Received data: Name - {name}, Email - {email}" return render_template('form.html') if __name__ == '__main__': app.run()
Redirects and Messages
After processing form data, it is often necessary to redirect the user to another page. Flask provides the redirect()
function for this purpose. Additionally, you can use the flash()
function to display messages to the user, such as success or error messages, after a redirect.
from flask import Flask, request, redirect, url_for, flash app = Flask(__name__) app.secret_key = 'secret' @app.route('/submit', methods=['POST']) def submit(): name = request.form['name'] email = request.form['email'] if not name or not email: flash('Error: Both name and email are required.') else: flash('Success: Form submitted successfully.') return redirect(url_for('home')) @app.route('/') def home(): return render_template('home.html') if __name__ == '__main__': app.run()