我想使用flask、WTForm 和flask_sqlalchemy 建立一个网站。有一个网页供用户通过WTForm提交信息,现在我想创建另一个页面来显示数据库中的所有数据。我想使用WTForm来做到这一点。在一本书中,示例如下:
def GetSchoolFormById(school_id):
school = orm.School.query.get(int(school_id))
if school is None:
return None
schoolform = SchoolForm()
schoolform.id.data = school.id
schoolform.name.data = school.name
schoolform.area_id.data = school.area_id
schoolform.area_name = school.area.name
schoolform.teachdesc.data = school.teachdesc
schoolform.address.data = school.address
schoolform.schooltype_id.data = school.schooltype_id
schoolform.schooltype_name = school.schooltype.name
schoolform.website.data = school.website
schoolform.distinguish.data = school.distinguish
schoolform.leisure.data = school.leisure
schoolform.threashold.data = school.threashold
schoolform.partner.data = school.partner
schoolform.artsource.data = school.artsource
schoolform.feedesc.data = school.feedesc
schoolform.longitude.data = school.longitude
schoolform.latitude.data = school.latitude
schoolform.schoolimages = school.schoolimages
schoolform.feature_ids.data = [x.feature_id for x in school.schoolfeatures]
schoolform.area_id.choices = g_choices_area
schoolform.schooltype_id.choices = g_choices_schooltype
schoolform.feature_ids.choices = g_choices_feature
return schoolform
但就我而言,我使用了 FieldList,所以我不知道如何像示例一样添加数据。
class ProjectForm(FlaskForm):
project_id = HiddenField('项目ID')
project_name = StringField('工程名称')
project_ST = DateField('起始时间', format='%Y-%m-%d')
project_FT = DateField('截止时间', format='%Y-%m-%d')
class ItemsForm(Form):
item_id = HiddenField('事件ID')
item_name = StringField('事件名称')
pre_item = SelectMultipleField('前驱事件')
# 暂定为string类型,加到date的%d里,具体我也不会,实现不了可以再改
last_time = StringField('持续时间')
class MainForm(FlaskForm):
items = FieldList(
FormField(ItemsForm)
)
@app.route('/view_items', methods=['GET', 'POST'])
def view_items():
form_one = ProjectForm()
form_two = MainForm()
if request.method == 'GET':
project = DBProject.query.filter_by(project_id=1).first().__dict__
print(project)
# 由于目前只有一个project,所以直接导入全部items数据
items = list(DBItem.query.filter().all())
form_one.project_id.data = project['project_id']
form_one.project_name.data = project['project_name']
form_one.project_ST.data = project['project_ST']
form_one.project_FT.data = project['project_FT']
for item in items:
print(item)
form_two.items.append_entry(ItemsForm(item))
return render_template('view_items.html', form_one=form_one, form_two=form_two)
当我测试我的代码时,从底部开始的第二行有一个错误,如下所示:</p>
TypeError: formdata should be a multidict-type wrapper that supports the 'getlist' method
我该如何处理?我应该使用其他方法将数据传递到 html 页面而不是 WTForm 吗?