使用WTF表单在Flask中编辑数据库字段并保留旧值

0 投票
2 回答
1604 浏览
提问于 2025-04-18 05:55

在我把一个值保存到数据库后,我正在显示一个编辑字段的HTML。

这个表单会自动填充之前的数据。

我该如何保存原始数据,以便检查哪些字段发生了变化呢?

这是我编辑视图的基本结构。

@app.route('/edit/<name>/<goal>/<strategy>/<task>', methods=['GET', 'POST'])
def edit_task(name,goal,strategy,task):
    ptask=models.Tasks.query.filter_by(task=task).first()
    form = task_form(obj=ptask)
    form.populate_obj(ptask)
    tform=task_form(request.values)
    if request.method == 'POST' and form.validate_on_submit():
        complete=tform.complete.data

        #check if complete changed 

        db.session.commit()
        return redirect(url_for('task_outline',name=name,goal=goal,strategy=strategy))
    return render_template('edit_task.html', tform=tform,form=form,ptask=ptask)

2 个回答

0

正如limasxgoesto0所建议的,我使用了get_history,这个方法有效。这里是我在测试的过程,以及我如何检查一个布尔值是否发生变化,并为新的True值分配一个新的日期。

从我的角度来看:

@app.route('/edit/<name>/<goal>/<strategy>/<task>', methods=['GET', 'POST'])
def edit_task(name,goal,strategy,task):
   ..... more view missing here.....
   ptask=models.Tasks.query.filter_by(task=task)
   if request.method == 'POST' and form.validate_on_submit(): 
        print 'now ',get_history(ptask, 'complete')[0]
        print 'before ',get_history(ptask, 'complete')[2]
        if get_history(ptask, 'complete')[0]==[True] and get_history(ptask, 'complete')[2]==[False]:
            print 'changed from false to true'
            ptask.completeDate=datetime.datetime.utcnow()
        if get_history(ptask, 'complete')[0]==[False] and get_history(ptask, 'complete')[2]==[True]:
            print 'changed from true to false'
            ptask.completeDate=None
    db.session.commit()    if request.method == 'POST' and form.validate_on_submit():
2

这很可能在Flask中也能用,不过我只在Pyramid中做过这个。

db.session.is_modified(ptask)
#returns True/False

撰写回答