Flask-WTF FileField在validate_on_submit

时间:2017-10-04 08:31:23

标签: python python-3.x csv flask flask-wtforms

我希望能够使用Flask-WTF FileField在Flask上传CSV文件,但无法通过validate_on_submit

这是我的看法。

@main.route('/upload', methods=['GET', 'POST'])
def upload_products():

    form = UploadForm()
    print (request.method)
    print (form.validate_on_submit())
    print (form.csv.data)
    if form.validate_on_submit():
        print ('valid on submit')
        f = form.csv.data
        print (f)
        return redirect(url_for('upload_products'))
    return render_template('upload.html', form=form)

这是我的表格

class UploadForm(FlaskForm):
    csv = FileField("")

这是我的html文件。

<div class="container">
  <h1 class="my-4">Hello! Upload files here!</h1>
</div>
<div class="container" >
  <form action="{{ url_for('main.upload_products') }}" method="post" enctype="multipart/form-data">
      {{form.csv}}
      <input type="submit" value="Submit">
  </form>
</div>
validate_on_submit

,我总是收到False值。 我也打印出form.csv.data,这是我得到的结果:

<FileStorage: '12347.csv' ('application/vnd.ms-excel')>

为什么validate_on_submit失败?我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

通过在我的模板上添加{{form.hidden_tag()}}来解决此问题。

<div class="container">
  <h1 class="my-4">Hello! Upload files here!</h1>
</div>
<div class="container" >
  <form action="{{ url_for('main.upload_products') }}" method="post" enctype="multipart/form-data">
      {{form.hidden_tag()}}
      {{form.csv}}
      <input type="submit" value="Submit">
  </form>
</div>