【问题标题】:Customizing FieldList views in Flask在 Flask 中自定义 FieldList 视图
【发布时间】:2015-11-29 14:55:42
【问题描述】:
如何实现 FieldList 视图,以便添加数据行、编辑现有行和删除现有行?这将在另一个模型的添加或编辑表单中。我一直在尝试阅读现有的文档,但我有点迷路了。这是一个文本模型:
Name Location Phone Number
----------------------------------------------------------------
John Doe New York 555-123-4567 [Edit] [Delete]
Jane Thomas New Jersey 555-987-6543 [Edit] [Delete]
Joe Bloggs Boston 123-456-7890 [Edit] [Delete]
[Add new row]
【问题讨论】:
标签:
python
flask
flask-wtforms
【解决方案1】:
您应该尝试在不使用 wtforms 的情况下执行此操作,因为表单通常指示使用一个提交按钮来更新或添加信息。由于您需要多种功能(因此需要多个提交按钮),因此您必须为每条记录使用多个表单。为了使事情变得不那么复杂并减少混乱,您应该只使用带有按钮的表格视图,这些按钮链接到将记录 ID 作为参数传递给各个视图的按钮。
呈现此类模板的示例如下:
views.py
@app.route('/update_records/')
def update_records():
data = model.get_all_records() #a list of dictionaries
if data is None:
return render_template('message.html', msg="No records exist yet")
headers = ['Name', 'Location', 'Phone Number'] #use these headers as table headers as well as keys to accessing the dictionaries. This way you won't display the IDs to your users but can still access them for the parameter passing
return render_template('update_records.html', data=data, headers=headers)
在模板中,您将呈现所有这些记录,并且针对每条记录,您将拥有诸如
之类的按钮
<button onClick="location.href='{{url_for('.delete_record', id_=row['_id_'], _external=True)}}'"> Delete
</button>