YouTip LogoYouTip

Flask Form

In Flask, form handling is a common requirement when building web applications. Handling form data involves receiving, validating, and processing user-submitted forms. Flask provides basic form handling functionality, but it's typically combined with the Flask-WTF extension to simplify form operations and validation. 1. **Basic Form Handling**: Use `request.form` to get form data. 2. **Using Flask-WTF**: Combine with WTForms for form handling and validation, simplifying form operations. 3. **Form Validation**: Use validators to ensure the validity of form data. 4. **File Upload**: Handle file uploads and save files. 5. **CSRF Protection**: Ensure forms are protected from cross-site request forgery attacks. ## 1. Basic Form Handling Flask provides a direct way to handle form data, using the request object to get submitted data. ### Create HTML Form templates/form.html file code: ## Example Form Example

action="/submit": Form data is submitted to the /submit path. method="post": Use POST method to submit data. ### Handle Form Data app.py file code: ## Example from flask import Flask, render_template, request app = Flask( __name__ ) @app.route('/') def form(): return render_template('form.html') @app.route('/submit', methods=['POST']) def submit(): name = request.form.get('name') email= request.form.get('email') return f'Name: {name}, Email: {email}' if __name__ =='__main__': app.run(debug=True) request.form.get('name') and request.form.get('email'): Get the submitted form data. ## 2. Using Flask-WTF Extension Flask-WTF is an extension that wraps WTForms, providing form handling and validation functionality, making form handling more concise and powerful. ### Install Flask-WTF pip install flask-wtf Configure Flask-WTF app.py file code: ## Example from flask import Flask, render_template, redirect, url_for from flask_wtf import FlaskForm from wtforms import StringField, EmailField, SubmitField from wtforms.validators import DataRequired, Email app = Flask( __name__ ) app.secret_key='your_secret_key'# Required for form protection class MyForm(FlaskForm): name = StringField('Name', validators=[DataRequired()]) email= EmailField('Email', validators=[DataRequired(), Email()]) submit = SubmitField('Submit') @app.route('/', methods=['GET','POST']) def form(): form = MyForm() if form.validate_on_submit(): name = form.name.data email= form.email.data return f'Name: {name}, Email: {email}' return render_template('form.html', form=form) if __name__ =='__main__': app.run(debug=True) ### Create Template to Support Flask-WTF Form templates/form.html file code: ## Example Form Example {{ form.hidden_tag() }}
{{ form.name.label }}
{{ form.name(size=32) }}
{{ form.email.label }}
{{ form.email(size=32) }}
{{ form.submit() }}
{{ form.hidden_tag() }}: Generates hidden fields to protect the form from CSRF attacks. {{ form.name.label }} and {{ form.name(size=32) }}: Render form fields and their labels. ## 3. Form Validation Flask-WTF and WTForms provide rich form validation functionality. You can use built-in validators or custom validators to ensure the validity of form data. ## Example from wtforms import Form, StringField, EmailField, SubmitField from wtforms.validators import DataRequired, Email, Length class MyForm(FlaskForm): name = StringField('Name', validators=[ DataRequired(), Length(min=1,max=50) ]) email= EmailField('Email', validators=[ DataRequired(), Email() ]) submit = SubmitField('Submit') * `DataRequired()`: Ensures the field is not empty. * `Length(min=1, max=50)`: Limits the minimum and maximum length of a string. * `Email()`: Validates whether the field is a valid email address. ## 4. File Upload Flask also supports handling file uploads. Uploaded files can be accessed through request.files. ### Create File Upload Form templates/upload.html file code: ## Example Upload File
enctype="multipart/form-data": Specifies the encoding type of form data, supporting file uploads. ### Handle File Upload app.py file code: ## Example from flask import Flask, request, redirect, url_for app = Flask( __name__ ) app.secret_key='your_secret_key' @app.route('/upload', methods=['POST']) def upload(): file= request.files.get('file') if file: filename =file.filename file.save(f'uploads/{filename}') return f'File uploaded successfully: {filename}' return'No file uploaded' if __name__ =='__main__': app.run(debug=True) request.files.get('file'): Get the uploaded file object. file.save(f'uploads/{filename}'): Save the file to the specified directory. ## 5. CSRF Protection Flask-WTF automatically provides CSRF protection for forms. You need to configure a secret key to enable CSRF protection and include a hidden CSRF token in the template. ### Configure CSRF Protection app.secret_key = 'your_secret_key' Add CSRF token in the template: ## Example {{ form.hidden_tag() }}
← Flask BlueprintsFlask Views Functions β†’