我结合了 Flask-WTF和Flask-upload来处理我的应用程序上的文件上传。
我的包版本是:
Flask-Uploads==0.2.1
Flask-WTF==0.11
WTForms==2.1
这是我的代码片段:
表格.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')
这是上传代码的片段:
@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)
但是,当我提交时,我收到以下错误:
AttributeError: 'FileField' object has no attribute 'has_file'
然后我尝试通过直接传递扩展来遵循这个文档,而不使用 Flask-Upload:
image = FileField('image', validators=[FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!')])
但我仍然遇到同样的错误。
那么,我的代码有什么问题..?请,任何帮助将不胜感激:)