我正在尝试使用Flask和WTForms的FileField表单字段构建一个应用程序,以将文件上传到Web服务器。帖子成功传递,但我很好奇为什么每次form.validate_on_submit()都会失败,即使特定验证器都成功了。这是我的表单(forms.py)、应用程序(main.py)和HTML模板(upload.html)的代码。
### forms.py
from flask.ext.wtf import Form
from flask.ext.wtf.html5 import EmailField
from flask.ext.wtf.file import FileField, FileRequired, FileAllowed
from wtforms import validators, ValidationError, SubmitField
class UploadForm(Form):
presentation = FileField('Presentation in Image Format', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!')])
submit = SubmitField("Send")
### main.py
from forms import UploadForm
from flask import render_template, url_for, redirect, send_from_directory
@app.route('/upload/', methods=('GET', 'POST'))
def upload():
form = UploadForm()
if form.validate_on_submit():
filename = secure_filename(form.presentation.file.filename)
print filename
form.presentation.file.save(os.path.join('uploads/', filename))
return redirect(url_for('uploads', filename=filename))
filename = None
return render_template('upload.html', form=form, filename=filename)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
### upload.html
{% for message in form.presentation.errors %}
<div class="flash">{{ message }}</div>
{% endfor %}
<form action="/upload/" method="POST" enctype="multipart/form-data">
{{ form.presentation.label }}
{{ form.presentation }}
{{ form.submit}}
</form>
有人知道为什么这个验证不起作用吗?或者我不应该使用validate_on_submit()吗?
form.validate()
替代form.validate_on_submit()
并将form = UploadForm()
更改为form = UploadForm(request.form)
。 - Odai Al-Ghamdi