Skip to content Skip to sidebar Skip to footer

FileAllowed Does Not Display An Error Message

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 fol

Solution 1:

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:

  • For invalid file format (audio file):

enter image description here

  • For valid file format (.png format)

valid upload

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:


Post a Comment for "FileAllowed Does Not Display An Error Message"