FileAllowed does not display an error message

余生长醉 提交于 2021-01-28 05:09:09

问题


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!")
    ])

回答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):

  • For valid file format (.png format)

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:

  • Displaying errors in WTF
  • File uploads using flask-wtf


来源:https://stackoverflow.com/questions/56225591/fileallowed-does-not-display-an-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!