使用 WTForms、SQLAlchemy & 更新记录烧瓶 [英] Updating a record with WTForms, SQLAlchemy & Flask

查看:34
本文介绍了使用 WTForms、SQLAlchemy & 更新记录烧瓶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我使用 WTForms 编辑表单时,它不会更新记录,而是将其添加为新记录.

Whenever I edit a form using WTForms, rather than it updating the record, it adds it as a new record.

我已经在 Flaskr 示例应用程序中复制了这个,所以这一定是我做错了什么,但我不确定是什么.

I have replicated this in the Flaskr example app so it must be something I am doing wrong but I am unsure what.

我在这里下载了 Flaskr:https://github.com/lepture/flask-wtf/tree/master/examples/flaskr

I downloaded the Flaskr here: https://github.com/lepture/flask-wtf/tree/master/examples/flaskr

这是一个简单的表单,有两个输入字段 - 标题和文本.可以提交表单,并将条目持久化到 sqlite 数据库.

It is a simple form with two input fields - Title and Text. The form can be submitted and the entries are persisted to a sqlite database.

我尝试修改它以允许更新条目.

I tried to modify it to allow the entries to be updated.

class Entry(db.Model):
    __tablename__ = "entries"
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Unicode(200))
    text = db.Column(db.UnicodeText)

class EntryForm(FlaskForm):
    title = TextField("Title", validators=[DataRequired()])
    text = TextAreaField("Text")
    submit = SubmitField("Share")

@app.route('/add', methods=['POST'])
def add_entry():
    if not session.get('logged_in'):
        abort(401)

    form = EntryForm()
    if form.validate():
        entry = Entry()
        form.populate_obj(entry)
        # entry.id=1
        db.session.add(entry)
        db.session.commit()
        flash('New entry was successfully posted')
    else:
        flash("Your form contained errors")

    return redirect(url_for('show_entries'))

我添加了一个新方法来使用现有条目填充表单:

I added a new method to populate the form with an existing entry:

@app.route('/edit/<int:id>', methods=['GET'])
def edit_entry(id=None):
    entries = Entry.query.order_by(Entry.id.asc())
    entry = Entry.query.get(id)
    form = EntryForm(obj=entry)
    return render_template('show_entries.html', entries=entries, form=form)

然后我通过表单添加了一个新条目并导航到 http://127.0.0.1:5000/edit/1,它确实使用我刚刚创建的条目填充了表单.

I then added a new entry via the form and navigated to http://127.0.0.1:5000/edit/1, which does indeed populate the form with the entry I just created.

然而,当表单被重新发布时,它不会更新数据库中的现有记录,而是插入一个新记录.我想可能是因为 ID 未在条目"对象中设置,但我什至在保存之前手动将其设置为 1,但它仍然尝试执行插入(并未能通过 PK 约束)而不是更新.

However, when the form is re-posted, rather than updating the existing record in the database, it inserts a new one. I thought perhaps it is because the ID is not set in the 'entry' object, but I even manually set it to 1 before saving it and it still tries to do an insert (and fails the PK constraint) rather than an update.

推荐答案

这是一个老问题,但这是我的方法,使用 Flask-SQLAlchemy.路由是独立的,但它们都调用相同的模板以避免重复.

This is an old question, but this was my approach, using Flask-SQLAlchemy. The routes are separate, but they both call on the same template to avoid repeating.

Form 可以将对象作为参数,并填充表单字段以进行更新".然后在表单上调用 populate_obj 方法来做到这一点,更改对象以反映新的表单字段.现在可以将新实例添加到数据库中.

Form can take the object as an argument, and populate the form fields for "updating". The populate_obj method then is called on the form to do just that, changing the object to reflect the new form fields. The new instance can now be added to the db.

@app.route("/add_item", methods=['GET', 'POST'])
def add_item():

    form = AddItem()

    if form.validate_on_submit():
        """Get instance of version from form data."""
        item = Item(field1=form.field1.data,
                    field2=form.field2.data,
                    field3=form.field3.data,
                    )
        db.session.add(item)
        db.session.commit()

    return render_template('add_item.html', form=form)


@app.route("/edit_item/<item_id>", methods=['GET', 'POST'])
def edit_item(item_id):

    item = db.session.query(Item).get(item_id)

    form = AddItem(obj=item)
    if form.validate_on_submit():
        form.populate_obj(item)
        db.session.add(item)
        db.session.commit()
        return redirect(url_for('home'))

    return render_template('add_item.html', form=form)

这篇关于使用 WTForms、SQLAlchemy &amp; 更新记录烧瓶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆