gpt4 book ai didi

Flask-WTForms FileField 未验证

转载 作者:行者123 更新时间:2023-12-03 17:12:54 24 4
gpt4 key购买 nike

我正在尝试构建一个应用程序以使用 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 token 。

解决办法很简单,把{{ 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>

关于Flask-WTForms FileField 未验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21155930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com