I combine Flask-WTF and Flask-upload to handle file upload on my App.
My package versions are:
Flask-Uploads==0.2.1
Flask-WTF==0.11
WTForms==2.1
Here is the snippet of my code:
forms.py
from flask_wtf import Form
from flask_wtf.file import FileAllowed, FileRequired
from wtforms.fields import (StringField, SubmitField, FileField)
from wtforms.validators import InputRequired, Length
from app import photos
class AddCourseForm(Form):
name = StringField('Course name', validators=[InputRequired(), Length(1, 100)])
image = FileField('image', validators=[FileRequired(), FileAllowed(photos, 'Images only!')])
submit = SubmitField('Add course')
And here is the snippet of the upload code:
@operator.route('/add-course', methods=['GET', 'POST'])
def add_course():
form = AddCourseForm()
if form.validate_on_submit():
course_name = form.name.data
filename = photos.save(request.files['image'], name="courses/" + course_name + "_course.")
course = Course(name=course_name, image=filename)
db.session.add(course)
db.session.commit()
flash('Successfully added {} '.format(course.course_name()) + 'course', 'success')
return redirect(url_for('operator.courses'))
return render_template('main/operator/add_course.html', form=form)
But, when I submitted that, I got this following error:
AttributeError: 'FileField' object has no attribute 'has_file'
Then I tried to following this documentation, without Flask-Upload by passing the extensions directly:
image = FileField('image', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!')])
But I still got the same error.
So, what's wrong with my code..? Please, any help would be appreciated :)