编辑表单会创建新数据

时间:2015-04-13 16:21:40

标签: python flask flask-sqlalchemy

我定义了一个路线和模板来编辑数据。相反,它会创建新数据。我该如何解决这个问题?

@home_blueprint.route('/table/<int:data_id>/edit', methods=['GET', 'POST'])
def edit(data_id):
    ed_form = EditTableForm(request.form)
    data_to_edit = db.session.query(Diary).filter_by(id=data_id)
    if ed_form.validate_on_submit():
        if ed_form.title.data:
            data_to_edit.title = ed_form.title.data
        if ed_form.weight.data:
            data_to_edit.weight = ed_form.weight.data
        if ed_form.kkal.data:
            data_to_edit.kkal = ed_form.kkal.data
        if ed_form.carbs.data:
            data_to_edit.carbs = ed_form.carbs.data
        if ed_form.proteins.data:
            data_to_edit.proteins = ed_form.proteins.data
        if ed_form.fats.data:
            data_to_edit.fats = ed_form.fats.data
        db.session.add(data_to_edit)
        db.session.commit()
        flash('New data was successfully posted. Thanks.')
        return redirect(url_for('home.table'))
    else:
        return render_template('edit.html', data_to_edit=data_to_edit, ed_form=ed_form, data_id=data_id)
    return render_template("edit.html", diary=diary)
  <table class="table table-bordered">
    <thead>
      <tr>
          <th>Product</th>
          <th>Weith</th>
          <th>Kkal</th>
          <th>Protein</th>
          <th>Fat</th>
          <th>Carbs</th>
      </tr>
    </thead>
    <tbody>
    {% for data in data_to_edit %}
    <tr>
        <form class="form-message" role="form" method="post" action="/table">
            {{ ed_form.csrf_token }}
            <td>{{ed_form.title(placeholder=data.title)}}</td>
            <td>{{ed_form.weight(placeholder=data.weight)}}</td>
            <td>{{ed_form.kkal(placeholder=data.kkal)}}</td>
            <td>{{ed_form.carbs(placeholder=data.carbs)}}</td>
            <td>{{ed_form.proteins(placeholder=data.proteins)}}</td>
            <td>{{ed_form.fats(placeholder=data.fats)}}</td>
            <td><button class="btn btn-sm btn-success" type="submit">Post</button></td>
        </form>
    </tr>
    {% endfor %}
    </tbody>
  </table>

链接到项目Git存储库。每个输入表的用户都有自己的id,我按id查询数据然后尝试编辑数据到目前为止没有运气:)

更新 我已将代码更改为:

data_to_edit = db.session.query(Diary).filter_by(id=data_id).first()
if ed_form.validate_on_submit():
    if not data_to_edit:
        data_to_edit = Diary(
        ed_form.title.data,
        ed_form.weight.data,
        ed_form.kkal.data,
        ed_form.carbs.data,
        ed_form.proteins.data,
        ed_form.fats.data,
        current_user.id
        )
        db.session.add(data_to_edit)
        db.session.commit()

但是没有运气,它不会改变旧数据,而是改变新广告。

1 个答案:

答案 0 :(得分:1)

问题是您在会话中再次添加对象,因此将其插入数据库。

示例代码

data_to_edit = db.session.query(Diary).filter_by(Diary.id=data_id).first()
if not data_to_edit:
    data_to_edit = Diary()
    db.session.add(data_to_edit)
...
# edit properties
...
db.session.commit()

我们的想法是只在新对象实际上是新的时才添加它。