我正在尝试构建一个应用程序,使用Flask和WTForms的FileField表单字段将文件上传到Web服务器。这篇文章已经成功完成,但我很好奇为什么form.validate_on_submit()每次都失败,即使特定的验证器都成功了。这是我的表单(forms.py),app(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()?
答案 0 :(得分:4)
Flask-WTF默认启用CRSF,如果您打印form.errors
,您将收到一条消息,告诉您需要csrf令牌。
解决方案很简单,将{{ form.csrf_token }}
放在模板中,或者禁用表单的CSRF,但你真的不应该这样做。
<form action="/upload/" method="POST" enctype="multipart/form-data">
{{ form.presentation.label }}
{{ form.presentation }}
{{ form.csrf_token }}
{{ form.submit}}
</form>
还可以快速将每个隐藏字段添加到表单hidden_tags
:
<form action="/upload/" method="POST" enctype="multipart/form-data">
{{ form.presentation.label }}
{{ form.presentation }}
{{ form.hidden_tag() }}
{{ form.submit}}
</form>