此代码应该更新数据库中与“post_id”匹配的帖子。但是它将更新表中的每个帖子。
代码已经过编辑,所以它可以正常工作。
@app.route('/update/<post_id>', methods=['GET', 'POST'])
def update(post_id):
if 'username' not in session:
return redirect(url_for('login'))
post = Post.query.get(post_id)
form = PostForm(obj=post)
if request.method == 'POST':
if form.validate() == False:
return render_template('update.html', form=form)
else:
Post.query.filter(Post.post_id==int(post_id)).update(dict(
title=form.title.data, body=form.body.data))
db.session.commit()
return redirect(url_for('retrieve'))
elif request.method == 'GET':
return render_template('update.html', form=form, post_id=post_id)
class Post(db.Model):
__tablename__ = 'posts'
post_id = db.Column(db.Integer, primary_key=True)
author = db.Column(db.String(128))
title = db.Column(db.String(128))
body = db.Column(db.Text)
def __init__(self, author, title, body):
self.author = author
self.title = title
self.body = body
<form method="POST" action="/update/{{post_id}}">
您必须检查post_id
与Post
class 属性传递的相等性post_id
。
Post.query.filter(Post.post_id==int(post_id)).update(dict(
title=form.title.data, body=form.body.data))
您的查询应该返回所有Post
记录,因为您检查post_id
了post_id
自身(而不是Post
类属性)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句