在Python Flask中显示关注的用户帖子时出现问题

时间:2018-10-11 19:08:31

标签: python sqlite flask sqlalchemy jinja2

所以我的项目有问题。我正在尝试显示用户的关注帖子,但未显示任何内容。我不知道问题是什么,因为没有任何错误显示。 This is what I am using to help me to query followed posts (page 158)

This is where the posts should be displayed. This gives the user the option to show all posts or just followed posts

什么也没显示。

这是我要在其后定义帖子的User类:

The function followed_post() is supposed to display the users followed posts

 @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

,在蓝图=“ 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,我认为这是主要问题所在:

this is the homepage.html .

This is a pastebin of the html

2 个答案:

答案 0 :(得分:0)

那是因为您只是在def followed_posts()属性中建立查询。

您应以.one().all()first()结尾。

另一方面,如果您使用的是SQLAlchemy,请查看混合属性。由于常规的Python属性有时会在同时查询实例和类属性时给您带来麻烦。

答案 1 :(得分:0)

据我所知,在您的HomePage端点中,您正在设置posts=pagination.items,在您的HTML中,您也在遍历post.items

在您的HTML中尝试:

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