我想将选择动态添加到WTForm SelectMutipleField。一旦用户在HTML中写入了项目的名称,然后单击“添加事项”按钮,则将有一个新行输入项目,其“ item_pre”选择框将被上方所有项目名称填充以供选择
但是,每当我单击按钮时,代码“ return render_template('create.html',project_form = project_form,item_form = item_form)“和”“都会收到一个名为“ TypeError:'NoneType'对象不可迭代”的错误。 {{item.item_pre}}”。该怎么办?
ItemForm.py
#include<glad/glad.h>
app.py
class ProjectForm(FlaskForm):
project_id = HiddenField('项目ID')
project_name = StringField('工程名称')
project_ST = DateField('起始时间', format='%Y-%m-%d')
project_FT = DateField('截止时间', format='%Y-%m-%d')
project_submit = SubmitField('确认')
# 改名为ItemForm,注意!
class ItemForm(Form):
item_id = HiddenField('事件ID')
item_name = StringField('事件名称')
item_pre = SelectMultipleField('前驱事件')
item_LT = StringField('持续时间') # 改名为item_LT
item_delete = SubmitField('删除') # 添加
class MainForm(FlaskForm):
item_list = FieldList( # 改名为item_list
FormField(ItemForm),
min_entries=0
)
item_add = SubmitField('添加事件') # 添加了item_add
item_submit = SubmitField('提交')
create.html
@app.route('/create', methods=['GET', 'POST'])
def create():
project_form = ProjectForm()
item_form = MainForm()
if request.method == 'GET':
return render_template('create.html', project_form=project_form, item_form=item_form)
if request.method == 'POST':
...
if item_form.item_add.data:
choice_list = []
for item in item_form.item_list.data:
item_dict = dict(item) # 每个item是一个dict类型,但是不能用dict的方法,需要先转换成dict类型的变量
print(item_dict)
item_values_list = list(item_dict.values()) # 字典中的值列表
choice_list.append(
(item_values_list[0] + item_values_list[1], item_values_list[0] + item_values_list[1]))
new_item = ItemForm()
print(choice_list)
new_item.item_pre.choices = choice_list
item_form.item_list.append_entry(new_item)
return render_template('create.html', project_form=project_form, item_form=item_form)
...