2016-05-03 92 views
0

我想用我的數據庫中的數據預填充我的表單以進行必要的更改並使用這些更改修改我的數據庫。 enter image description here 但是,當我運行下面的代碼時,當form.validate_on_submit()方法被初始化時,表單的數據是來自數據庫的預填充數據,而不是編輯版本。我如何訪問表單數據的編輯值?提交編輯從數據庫預填充Flask-WTForm數據

@auth.route('/edit_projects', methods=['GET', 'POST']) 
@auth.route('/edit_projects/<project>', methods=['GET', 'POST']) 
@login_required 
def edit_projects(project=None): 
    form = ProjectForm() 
    project_db = Project.query.all() 
    edit_project_db = Project.query.filter_by(id=project).first() 
    if project != None: 
     form.name.data=edit_project_db.name 
     form.project_brief.data=edit_project_db.project_brief 
     form.project_description.data=edit_project_db.project_description 

    if form.validate_on_submit(): 
     edit_project_db.name = form.name.data 
     edit_project_db.project_brief = form.project_brief.data 
     edit_project_db.project_description = form.project_description.data 
     db.session.commit() 
     flash('Product %s updated.' %(str(form.name.data))) 

回答

1

我認爲它可以幫助「GET」和「POST」之間的區別,在「GET」你預填充字段,但在「POST」要看到,如果用戶實際上已經編輯的表格內容。

我會分裂的代碼,如:

if request.method == 'GET': 
    # prepopulate 
    if project != None: 
     form.name.data=edit_project_db.name 
     form.project_brief.data=edit_project_db.project_brief 
elif request.method == 'POST': 
    # check form validates 
    if form.validate_on_submit(): 
     # keep the rest as it is 
     ... 

希望這提供了一些幫助。