FileAllowed不显示错误消息

时间:2019-05-20 17:26:17

标签: python flask flask-wtforms wtforms

我正在使用WTForms。我正在对文件上传应用验证,并将其限制为jpg,png和pdf格式。但是,如果我输入错误,则不会出现错误消息。

我遵循了本教程 https://flask-wtf.readthedocs.io/en/stable/form.html

photo = FileField('photo', validators=[
        FileRequired(),
        FileAllowed(['png', 'pdf', 'jpg'], "wrong format!")
    ])

1 个答案:

答案 0 :(得分:1)

默认情况下,如果验证失败,flask-wtf不会显示任何错误消息。

可以捕获并显示每个单独字段或所有字段的错误消息。

这是在flask-wtf中进行验证的文件上传示例。

文件夹结构:

.
├── 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>

输出:

  • 对于无效的文件格式(音频文件):

enter image description here

  • 获取有效的文件格式(.png格式)

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

运行应用程序:

export FLASK_APP=app.py
export FLASK_ENV=development
flask run

参考: