编辑 我通过将变量名称从 post_id 更改为 post_num 解决了这个问题。我猜测在传递参数时,相似性在某处造成了歧义错误。
在我的 post.html HTML 中:
{% if current_user.is_authenticated %}
{% if current_user.has_liked_post(post) %}
<a href="{{ url_for('users.like_post', post_id=post.id, action='unlike') }}">Unlike</a>
{% else %}
<a href="{{ url_for('users.like_post', post_id=post.id, action='like') }}">Like</a>
{% endif %}
{% endif %}
python路由(帖子和用户都是注册蓝图):
@users.route('/like/<int:post_id>/<action>')
@login_required
def like_post(post_id, action):
this_id = post_id
post = Post.query.filter_by(id=post_id).first_or_404()
if action == 'like':
current_user.like_post(post)
db.session.commit()
if action == 'unlike':
current_user.unlike_post(post)
db.session.commit()
return redirect(url_for('posts.post', post_id=this_id))
@posts.route("/post/<int:post_id>")
def post(post_id):
post = Post.query.get_or_404(post_id)
print(post)
return render_template('post.html', title=post.title, post=post)
当我点击“喜欢”按钮时,它出于某种原因将我重定向到主索引页面。更令人困惑的是它似乎正在工作,因为它在数据库中正确注册了“喜欢”,当我导航回帖子时,它会根据用户是否“喜欢”正确显示“喜欢”或“不喜欢”发布。
此外,当我点击“喜欢”或“不喜欢”时,它会执行@posts.post 路由内的 print(post) 函数。这意味着重定向似乎正确发生,并且它获得了正确的 post_id 并将该信息打印到 python 控制台。但是,它随后出于某种原因重定向到主索引,而不是停留在/呈现/post/post_id 的页面。如果我以任何其他方式访问此 post/post_id 页面,它显然也不会重定向到索引页面。
我在另一个“update_post”函数中也有相同的“return redirect(url_for('posts.post', post_id=this_id))”语法,这似乎没有相同的问题,它重定向并保持不变页面应有的方式。
无论如何,我的 post.html 文件中没有一行或下面的任何行都引用了索引页。