我有这样的表格:
class TimeScheduleForm(FlaskForm):
schedule_day = SelectField(choices=day_name_list)
start_at = TimeField()
end_at = TimeField()
这是我在 Jinja2 上传递它的方式:
{{ f.begin_form(time_schedule_form) }}
{{f.render_form_field(time_schedule_form.schedule_day)}}
{{f.render_form_field(time_schedule_form.start_at)}}
{{f.render_form_field(time_schedule_form.end_at)}}
{{ f.end_form() }}
该表格的目的是在我的项目案例中保存课程安排,但它只可以节省一天。
但是现在我想动态地获取该值,可以说我想在一周内制定3个时间表。
我可以使用以下代码进行操作:
class TimeScheduleForm(FlaskForm):
schedule_day_1 = SelectField(choices=day_name_list)
schedule_day_2 = SelectField(choices=day_name_list)
schedule_day_3 = SelectField(choices=day_name_list)
start_at_1 = TimeField()
start_at_2 = TimeField()
start_at_3 = TimeField()
end_at_1 = TimeField()
end_at_2 = TimeField()
end_at_3 = TimeField()
然后在 Jinja2 上执行以下操作:
{{ f.begin_form(schedule_form) }}
{{f.render_form_field(time_schedule_form.schedule_day_1)}}
{{f.render_form_field(time_schedule_form.schedule_day_2)}}
{{f.render_form_field(time_schedule_form.schedule_day_3)}}
{{f.render_form_field(time_schedule_form.start_at_1)}}
{{f.render_form_field(time_schedule_form.start_at_2)}}
{{f.render_form_field(time_schedule_form.start_at_3)}}
{{f.render_form_field(time_schedule_form.end_at_1)}}
{{f.render_form_field(time_schedule_form.end_at_2)}}
{{f.render_form_field(time_schedule_form.end_at_3)}}
{{ f.end_form() }}
但这似乎不是最佳实践。
然后我使它像这样:
class TimeScheduleForm(FlaskForm):
schedule_day = SelectField(choices=day_name_list)
start_at = TimeField()
end_at = TimeField()
然后在 Jinja2 :
{% for field in range(how_many_times_in_a_week) %} <!-- how_many_times_in_a_week is a variable which is contain 3 as the value -->
{{ f.render_form_field(time_schedule_form.schedule_day) }}
{{ f.render_form_field(time_schedule_form.start_at) }}
{{ f.render_form_field(time_schedule_form.end_at) }}
{% endfor %}
然后我尝试获取该值:
print('test', time_schedule_form.schedule_day.data)
print('test', time_schedule_form.start_at.data)
print('test', time_schedule_form.end_at.data)
但是上面的结果只是在循环中获取第一个字段值。
然后我尝试像这样获取它:
for data in time_schedule_form.schedule_day.data:
print('test', data)
结果仍然只是获取第一个字段值,甚至比我想要的还要差。
因此,如何遍历表单字段并获取值..?,是否可能..?,最佳实践是什么?。
编辑:我想要的是这样的结果:
但是上面的屏幕截图只是使用以下代码通过HTML手动形成:
<body>
<form action="" method="post">
Schedule Day <br>
<input type="text" name="schedule"><br>
Start at <br>
<input type="time" name="start_at"><br>
End at <br>
<input type="time" name="end_at"><br><br>
Schedule Day <br>
<input type="text" name="schedule"><br>
Start at <br>
<input type="time" name="start_at"><br>
End at <br>
<input type="time" name="end_at"><br><br>
Schedule Day <br>
<input type="text" name="schedule"><br>
Start at <br>
<input type="time" name="start_at"><br>
End at <br>
<input type="time" name="end_at"><br><br>
<input type="submit">
</form>
</body>
现在,我想通过循环的 Flask-WTF 来做到这一点。