Handling form data
In this tutorial, we'll cover how to handle form data in Flask, an essential skill for any aspiring Flask developer. By the end of this guide, you'll be able to accept, validate, and process form data within your Flask applications.
What are Flask Forms?
Flask forms are a way to accept input from users on your website. They can include text fields, checkboxes, radio buttons, file upload fields, and more. Whenever a user fills out a form on your website, that data is sent to your application as form data.
Setting Up a Basic Flask Form
To start accepting form data, you first need to create a form. For the sake of simplicity, we'll create a simple form with a single text field.
<form method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<input type="submit" value="Submit">
</form>
This form, when submitted, will send a POST request to the server with the entered username.
Accessing Form Data in Flask
To access this data in Flask, you use the request
object's form
attribute, which contains a dictionary of all form data sent with the request.
Here's a basic route that prints out the submitted username:
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def handle_form():
username = request.form['username']
print('Username: ', username)
return 'Form Submitted!'
Validating Form Data
Now, accepting user input without any validation is generally a bad idea. You should always validate form data before using it.
Flask provides the wtforms
library for form validation. Here's how you could use it to ensure that the username field isn't empty:
from flask import Flask, request
from wtforms import Form, StringField, validators
app = Flask(__name__)
class RegistrationForm(Form):
username = StringField('Username', [validators.Length(min=1)])
@app.route('/', methods=['POST'])
def handle_form():
form = RegistrationForm(request.form)
if form.validate():
print('Username: ', form.username.data)
return 'Form Submitted!'
else:
return 'Form Validation Failed!'
Conclusion
In this tutorial, we've covered the basics of handling form data in Flask. There's a lot more to learn, such as handling file uploads, protecting against CSRF attacks, and more. But this should give you a good foundation to start accepting and processing user input in your Flask applications. As always, remember to validate your form data before using it!