'Flask form validation message error not displayed
I want to create a field for uploading multiple files, these must be in wav format. Since there is no validator that allows me to do this I created a custom one. The validation works correctly, but I can't get the error message to show. Can anyone tell me what I'm doing wrong?
Custom validator class
class MultiFileAllowed(object):
def __init__(self, upload_set, message=None):
self.upload_set = upload_set
self.message = message
def __call__(self, form, field):
if not (all(isinstance(item, FileStorage) for item in field.data) and field.data):
return
for data in field.data:
filename = data.filename.lower()
if isinstance(self.upload_set, Iterable):
if any(filename.endswith('.' + x) for x in self.upload_set):
return
raise ValidationError(self.message)
if not self.upload_set.file_allowed(field.data, filename):
raise ValidationError(self.message)
Form class
class PreprocessingForm(FlaskForm):
file = FileField('Insert XLS file', validators=[FileRequired(), FileAllowed(['xls', 'xlsx'],
'Wrong file extension, insert XLS or XLSX file')])
files = MultipleFileField('Insert wav files', validators=[
InputRequired(),
MultiFileAllowed(['wav'], 'Wrong file extension, insert WAV file')
])
submit = SubmitField('Submit')
View
@preprocessing_blueprint.route('/preprocessing', methods=['GET', 'POST'])
def preprocessing():
form = PreprocessingForm()
if form.validate_on_submit() and request.method == 'POST':
#for file in form.files.data:
#file_filename = secure_filename(file.filename)
#data.save(os.path.join(current_app.config['UPLOAD_FOLDER'], data_filename))
#files_filenames.append(file_filename)
#print(files_filenames)
return '<h1> Doing preprocessing </h1>'
return render_template('preprocessing.html', form = form)
Template html
<form method="POST", enctype=multipart/form-data>
<br>
<div class="d-flex justify-content-center">
<div class="w-25 p-3" style="background-color: #eee;" >
<h3>This is the preprocessing page.</h3>
{# This hidden_tag is a CSRF security feature. #}
{{ form.hidden_tag() }}
{{form.file.label(class="form-label")}} {{form.file(class="form-control")}}
{% if form.file.errors %}
{% for error in form.file.errors %}
<p style="color:red;">{{ error }}</p>
{% endfor %}
{% endif %}
<br>
{{form.files.label(class="form-label")}} {{form.files(class="form-control")}}
{% if form.files.errors %}
{% for error in form.file.errors %}
<p style="color:red;">{{ error }}</p>
{% endfor %}
{% endif %}
<br>
{{ form.submit(class="btn btn-primary mb-3") }}
</div>
</div>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
