如何跟踪Flask-WTF中的表单字段更改?

时间:2013-05-14 09:13:32

标签: python google-app-engine flask wtforms flask-wtforms

我有成员字段的模型,如下所示:

class Team(db.Model):
    --- some fields ---
    members = ListProperty(db.Key) # Using App Engine datastore as backend.

我使用Flask-WTFforms使用此模型创建表单。在创建新团队时,用户将在表单中选择一些成员并保存。用户还可以编辑团队表单并更改成员字段(可以添加或删除成员)。我想通过将其与成员字段中存储的先前数据进行比较来检查添加或删除的成员数量。同样适用于其他领域。

我用会话实现了这个目标:

def edit_team(key):

k = db.Key(key)
team = db.get(k)
form = TeamForm(obj = team)
if not form.is_submitted(): # Indicates GET request
    session[str(g.user.user_id() + 'prev_members'] = form.members.data
if form.validate_on_submit():
    form.populate_obj(project)
    # I will use session data with new form.members.data to do further processing.

这是处理这种情况的正确方法吗? 谢谢你的帮助......

1 个答案:

答案 0 :(得分:0)

您的代码存在问题

team = db.get(k)
form = TeamForm(obj = team)

如果请求是GET,则必须从模型加载对象的数据。但是,如果请求为POST(或PUTPATCH),则表示您需要阅读请求正文以形成对模型进行适当更新。看起来你正在使用k变量作为模型指标的关键。

k = db.Key(key)
team = db.get(k)
if request.method == "GET":
    # create form from the model
    form = TeamForm(obj = team)

elif request.method == "POST":
    # update model with the form
    form = TeamForm() #flask-wtf automatically reads from request object
    # validate, update, delete, ...