I am using WTForms. I am applying validation on file upload and restricted it to jpg,png and pdf format only. however if i give an incorrect input, no error message appears.
I followed this tutorial https://flask-wtf.readthedocs.io/en/stable/form.html
photo = FileField('photo', validators=[
FileRequired(),
FileAllowed(['png', 'pdf', 'jpg'], "wrong format!")
])
By default, flask-wtf does not show any error message if validation fails.
Error messages can be caught and shown for each individual field or for all fields together.
Here is an example of file upload with validation in flask-wtf.
Folder structure:
.
├── app.py
├── forms.py
├── requirements.txt
└── templates
└── upload.html
app.py:
from flask import Flask, render_template
from forms import FileUploadForm
app = Flask(__name__)
app.secret_key = 'learnflask'
@app.route('/upload', methods=['GET', 'POST'])
def upload():
form = FileUploadForm()
if form.validate_on_submit():
f = form.photo_or_pdf_file.data
return f.filename
return render_template('upload.html', form=form)
forms.py:
from flask_wtf import FlaskForm
from wtforms import SubmitField
from flask_wtf.file import FileField, FileAllowed, FileRequired
class FileUploadForm(FlaskForm):
photo_or_pdf_file = FileField('photo', validators=[
FileRequired(),
FileAllowed(['png', 'pdf', 'jpg'], "wrong format!")
])
submit = SubmitField('Upload')
templates/upload.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<style>
.validation_error{
color: red;
}
</style>
</head>
<body>
<form method="POST" enctype="multipart/form-data">
{{ form.csrf_token }}
{{ form.photo_or_pdf_file.label }}<br>{{ form.photo_or_pdf_file }}
<span class="validation_error">{{ ', '.join(form.photo_or_pdf_file.errors) }}</span><br>
{{ form.submit }}<br>
</form>
</body>
</html>
Output:


requirements.txt:
Click==7.0
Flask==1.0.3
Flask-WTF==0.14.2
itsdangerous==1.1.0
Jinja2==2.10.1
MarkupSafe==1.1.1
pkg-resources==0.0.0
Werkzeug==0.15.4
WTForms==2.2.1
Running the application:
export FLASK_APP=app.py
export FLASK_ENV=development
flask run
Reference:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With