我正在尝试使用FieldList和FormField从数据库中生成学生的动态列表。这些字段是使用数据库中的数据生成的,但是如果我尝试从前端更改某些内容,则后端仅接收起始数据(例如,对于复选框,它只会得到 False)
形式:
class Beneficiary_Migration_Entry_Form(FlaskForm):
name = StringField('')
id = StringField('')
school = SelectField('', validate_choice=False)
student_class = SelectField('', validate_choice=False)
migrate = BooleanField('')
class Beneficiary_Migration_Form(FlaskForm):
entry_form_list = FieldList(FormField(Beneficiary_Migration_Entry_Form))
submit = SubmitField('Submit')
路线
@app.route('/migration/student/<school_year_id>', methods=['GET', 'POST'])
@login_required
def student_migration_page(school_year_id):
school_year_id = int(school_year_id)
school_year = School_Year.query.filter(School_Year.id==school_year_id).first()
entry_form_list = []
school_list = Database_Manager.get_school_list(current_user)
school_choices = get_school_list()
entries = Student.query.filter(Student.user_id==current_user.id).all()
for entry in entries:
form = Beneficiary_Migration_Entry_Form(
name=entry.name,
id=entry.id,
)
id_str = str(entry.id)
form.name.name = 'name-' + id_str
form.school.name = 'school-' + id_str
form.migrate.name = 'migrate-' + id_str
form.student_class.name = 'student_class-' + id_str
form.id.name = 'id-' + id_str
form.school.choices = school_choices
form.student_class.choices = [('','')]
entry_form_list.append(form)
migration_form = Beneficiary_Migration_Form()
migration_form.entry_form_list = entry_form_list
school_map = Database_Manager.get_schools_map(current_user)
if migration_form.submit.data:
for form in migration_form.entry_form_list:
print(form.migrate.data)
return redirect(url_for('migration_page', school_year_id=school_year_id))
return render_template('migration-elev.html', school_map=school_map,school_year=school_year, migration_form=migration_form)
前端:
<form action="" method="post">
{{ migration_form.hidden_tag() }}
<table class="table table-striped table-dark" style="text-align: center;">
<thead class="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nume</th>
<th scope="col">Scoala</th>
<th scope="col">Clasa/ Grupa</th>
<th scope="col">Transfer</th>
</tr>
</thead>
<tbody>
{% for form in migration_form.entry_form_list %}
{{ form.hidden_tag() }}
<tr>
<td>{{form.id.value}}</td>
<td>{{form.name}}</td>
<td>{{form.school}}</td>
<td>{{form.student_class}}</td>
<td>{{form.migrate}}</td>
</tr>
{% endfor %}
</tbody>
</table>
<p>{{ migration_form.submit(class_="btn btn-primary") }}</p>
</form>
起初它只从 FieldList 的第一个条目中获取数据,但我发现我需要使用唯一的名称。
我尝试使用 validate_on_submit 但我得到AttributeError: 'Beneficiary_Migration_Form' object has no attribute 'copy'。
我也尝试使用字典和命名元组来加载数据,但我得到了相同的结果。