首页 > 解决方案 > 在 Python Flask 中显示关注的用户帖子时出现问题

问题描述

所以我的项目有问题。我正在尝试显示用户的以下帖子,但没有显示任何内容。我不知道问题是什么,因为没有显示错误。这就是我用来帮助我查询关注的帖子的方法(第 158 页)

这是应该显示帖子的地方。这使用户可以选择显示所有帖子或仅显示关注的帖子

但是什么都没有显示。

这是我定义关注帖子的用户类:

函数followed_post() 应该显示用户关注的帖子

 @property
def followed_posts(self):
    return Post.query.join(Follow, Follow.followed_id == Post.user_id).filter(Follow.follower_id == self.id)

在我的主要路线中,我有;

@main.route('/all')
@login_required
def show_all():
    resp = make_response(redirect(url_for('main.compscipost')))
    resp.set_cookie('showed_followed', '' , max_age = 
    30*24*60*60)
return resp

@main.route('/followed')
@login_required
def show_followed():
   resp = make_response(redirect(url_for('main.HomePage')))
   resp.set_cookie('showed_followed', '1', max_age = 30*24*60*60)
return resp

在 blueprint =' main' routes.py 中,我的主页的功能是:

@main.route('/')
@main.route('/home')
def HomePage():
  page = request.args.get('page', 1, type = int)
  showed_followed = False
  if current_user.is_authenticated:
    showed_followed = bool(request.cookies.get('showed_followed', ''))
  if showed_followed:
     query= current_user.followed_posts
  else: 
    query = Post.query
  pagination = 
query.order_by(Post.date_posted.desc()).paginate(page = page, 
per_page = 5, 
        error_out = False)
posts = pagination.items
return render_template("HomePage.html", posts =posts, 
showed_followed = showed_followed , 
    pagination = pagination)

最后对于我的 homepage.html,我认为这是主要问题所在:

这是 homepage.html 。

这是html的pastebin

标签: pythonsqliteflasksqlalchemyjinja2

解决方案


据我所知,在您的HomePage端点中,您正在设置posts=pagination.items,并且在您的 HTML 中,您也在循环post.items

在你的 HTML 中试试这个:

{% for post in posts %}
# ...
{% endfor %}

推荐阅读