如何通过Wtforms 的 Fieldlist(FormField(XXX) 功能实现在1个View中的1张表格(table)内实现1个Submit 同时提交多行记录到数据库?


#1

在学习了Flask Book 和 Flask 进阶之后,尝试编写一个检查表提交程序。
初步的想法是在一个Suvey 视图内的1个表格(table)内实现检查表项目的显示和数据的提交。
该检查表从数据库内导入检查清单,并在每行记录的前面几列显示检查表,后面几列里面对每个检查项目的结果输入。
在完不定行数据的输入之后,通过一个提交(submit)将这些记录存进数据库,并可以在下次打开视图的时候在对应输入的列预先填充上次提交的数据以供修改。
#forms.py

class InputRecordForm(FlaskForm):
    id = IntegerField('Record ID')
    result = SelectField('Result', coerce=str)
    particular = TextAreaField('Particular')

class InputGirdTableForm(FlaskForm):
    girdtbrecords = FieldList(FormField(InputRecordForm))

#views.py

@admin.route('/surveys/<int:id>', methods=['GET', 'POST'])
@login_required
def survey(id):
    form = InputGirdTableForm()
    survey_job = SurveyJob.query.filter_by(id=id).first()
    ship_id = survey_job.survey_request.ship.id
    checklists = Checklist.query.filter_by(ship_id=ship_id, active=True).all()
    if form.validate_on_submit():
        # from collections import deque
        # queue = deque(form.girdtbrecords.data) 
        form_record = reversed(form.girdtbrecords)
        for checklist in checklists:
            # record = queue.popleft()
            # checklist.result = record['result']
            # checklist.particular = record['particular']
            record = form_record.pop_entry()
            checklist.result = record.result.data
            checklist.particular = record.particular.data
            db.session.add(checklist)
        db.session.commit()
        return render_template('admin/survey.html', form=form, survey_job=survey_job, checklists=checklists)
    # for checklist in checklists:
    #     from werkzeug.datastructures import MultiDict
    #     record_form = InputRecordForm(MultiDict([('result', checklist.result), ('particular', checklist.particular)]))
    #     form.girdtbrecords.append_entry(record_form)
    return render_template('admin/survey.html', form=form, survey_job=survey_job, checklists=checklists)

我目前没搞清楚如何在 template/survey.html 内实现对 FiledList内的InputRecordForm 的field 正确渲染。