WTForms FileField无法验证
我正在尝试构建一个应用程序,使用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()?
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>
链接地址: http://www.djcxy.com/p/61755.html