1

I want to be able to upload a CSV file on Flask using Flask-WTF FileField, but can't get pass the validate_on_submit .

This is my view.

@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)

this is my form

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

this is my html file.

<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>

on validate_on_submit, I am always receiving a False value. I also printed out form.csv.data and this is the result I got:

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

Why is it failing on validate_on_submit? Did I miss something?

ellaRT
  • 1,346
  • 2
  • 16
  • 39
  • 1
    I guess it's the CSRF issue. Can you print out the `form.errors`? It should said "CSRF token missing". If so, check this answer: https://stackoverflow.com/a/21501593/2644759 – Philip Tzou Oct 04 '17 at 23:25
  • you are right, error is `The CSRF token is missing.` – ellaRT Oct 04 '17 at 23:44

1 Answers1

0

Fixed this by adding {{form.hidden_tag()}} on my template.

<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>
ellaRT
  • 1,346
  • 2
  • 16
  • 39