【问题标题】:flask edit a database field and retain previous value using wtf form烧瓶编辑数据库字段并使用 wtf 表单保留以前的值
【发布时间】:2014-05-10 07:04:02
【问题描述】:

将值保存到我的数据库后,我正在呈现一个 edit_field 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)

【问题讨论】:

    标签: python flask flask-sqlalchemy flask-wtforms


    【解决方案1】:

    这很可能会在 Flask 中工作,但是我只使用 Pyramid 做过这个

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

    【讨论】:

    • 很好的建议。它有效,但是您是否碰巧知道如何检查特定字段是否已修改。在文档中找不到它。试了一下 db.session.is_modified(ptask.complete.data) AttributeError: 'bool' object has no attribute 'data'
    • 我找不到任何简单的方法来做到这一点。您可以尝试遍历您的列并按照stackoverflow.com/questions/3645802/… 使用 sqlalchemy.orm.attributes.get_history
    • 是的!您使用 get_history 的建议效果很好。我会发布我的解决方案
    【解决方案2】:

    正如 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():
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      相关资源
      最近更新 更多