Question

I'm trying to build an app to upload a file to a web server using Flask and WTForms' FileField form field. The post is going through successfully but I am curious as to why form.validate_on_submit() fails each time even though the particular validators all succeed. Here is my code for the form (forms.py), the app (main.py) and the html template (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>

Does anyone know why this might not be validating? Or should I not be using validate_on_submit()?

Was it helpful?

Solution

Flask-WTF enables CRSF by default, if you print the form.errors, you will get a message that tells you a csrf token is required.

The solution is simple, put {{ form.csrf_token }} in your template, or disable CSRF of the form, but you really shouldn't do such thing.

<form action="/upload/" method="POST" enctype="multipart/form-data">
 {{ form.presentation.label }}
 {{ form.presentation }}
 {{ form.csrf_token }}
 {{ form.submit}}
</form>

There is also a quick way to add every hidden fields to the form hidden_tags:

<form action="/upload/" method="POST" enctype="multipart/form-data">
 {{ form.presentation.label }}
 {{ form.presentation }}
 {{ form.hidden_tag() }}
 {{ form.submit}}
</form>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top