【问题标题】:Need SQLAlchemy WTForms Flask append children to parent form example需要 SQLAlchemy WTForms Flask 将子级附加到父表单示例
【发布时间】:2020-02-03 22:05:12
【问题描述】:

虽然https://wtforms.readthedocs.io/en/stable/ 有 WTForms 的文档,https://wtforms-alchemy.readthedocs.io/en/latest/ 也有 WTForms-Alchemy 的文档,但文档确实可以通过包含一些示例来改进,因为它们将使用 Flask 实现。我面临的一个挑战是创建一个简单的表单,允许用户更新父对象的父对象和子对象。另外两篇 StackOverflow 帖子解决了这一挑战。第一个(这是我自己的,位于 When using wtforms and sqlalchemy a form with a parent-child relationship appends new children to the db rather than updating existing children )是完整的,但包含我怀疑的东西。第二个很好,但没有显示如何将表单保存在烧瓶中:Append entry to FieldList with Flask-WTForms using AJAX。有人知道更新父对象及其子对象的表单的完整且正确的工作烧瓶-sqlalchemy-wtforms 示例吗?该表单应允许用户添加其他子项并对其进行编辑,而不是简单地将父项与现有子项关联。

【问题讨论】:

标签: flask sqlalchemy wtforms


【解决方案1】:

我终于想出了一个不会让人觉得笨拙的解决方案。完整的回购(仍然非常空闲)在这里:https://github.com/lfernandez55/3200_wtf_parent_child_example。下面是 update_registration 视图,详细说明了表单信息如何在更新中持久保存:

@app.route('/update_registration', methods=['GET', 'POST'])
def update_registration():
    parentObj = Parent.query.filter(Parent.id == 1).first()
    form = ParentForm(id=parentObj.id, name=parentObj.name, children=parentObj.children)

    if form.add_child.data:
        form.children.append_entry()
        return render_template('update_registration.html', form=form)
    if form.remove_child.data:
        popped_entry = form.children.pop_entry()
        child = Child.query.filter(Child.id == popped_entry.data['id']).first()
        db.session.delete(child)
        db.session.commit()
        return render_template('update_registration.html', form=form)
    if form.validate_on_submit():
        for child in form.children.data:
            if child['id'] != "":
                childObj = Child.query.filter(Child.id == child['id']).first()
                childObj.name=child['name']
                childObj.age=child['age']
            else:
                childObj = Child(name=child['name'],age=child['age'])
            parentObj.children.append(childObj)
        db.session.add(parentObj)
        db.session.commit()
        flash('Parent [and children] Updated!!')
        return redirect(url_for('home_page'))
    return render_template('update_registration.html', form=form)

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多