从数据库提交已编辑的Prepopulate Flask-WTForm数据

时间:2016-05-03 10:31:24

标签: python flask flask-wtforms

我想使用数据库中的数据预先填充表单,以进行必要的更改并使用这些更改修改我的数据库。enter image description here 但是,当我在下面运行以下代码时,初始化form.validate_on_submit()方法时,表单的数据是来自数据库的预先填充的数据,而不是编辑后的版本。如何访问表单数据的编辑值?

@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 个答案:

答案 0 :(得分:1)

我认为这有助于区分GET&#39;和&#39; POST&#39;,&#39; GET&#39;您预填充字段,但在&#39; POST&#39;您想查看用户是否实际编辑了表单内容。

我会将代码拆分为:

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
        ...

希望这能提供一些帮助。