如何在Flask应用程序中显示喜欢帖子的用户列表



我是Flask的新手,我通过关注Corey Schafer和Miguel Grinberg的视频,使用Flask创建了一个社交媒体博客,我还加入了其他功能,如点赞和评论帖子。我加入的所有功能都正常工作,但我无法查看喜欢帖子的用户。

这是我的routes.py文件,它有like和ViewLikers路由

@app.route('/like/<int:post_id>/<action>')
@login_required
def like_action(post_id, action):
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(request.referrer) 
@app.route('/like/<int:post_id>/viewLikes')
@login_required
def viewLikers(post_id):
post = Post.query.get_or_404(post_id)
return render_template('viewLikes.html', likers=post.get_likers())

这是我的models.py文件

class PostLike(db.Model):
__tablename__ = 'PostLike'
id = db.Column(db.Integer, primary_key=True)
users_id = db.Column(db.Integer, db.ForeignKey('user.id'))
post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
password = db.Column(db.String(60), nullable=False)
posts = db.relationship('Post', backref='author', lazy=True)
followed = db.relationship(
'User', secondary=followers,
primaryjoin=(followers.c.follower_id == id),
secondaryjoin=(followers.c.followed_id == id),
backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')
liked = db.relationship(
'PostLike',
foreign_keys='PostLike.users_id',
backref='user', lazy='dynamic')
def like_post(self, post):
if not self.has_liked_post(post):
like = PostLike(users_id=self.id, post_id=post.id)
db.session.add(like)
def unlike_post(self, post):
if self.has_liked_post(post):
PostLike.query.filter_by(
users_id=self.id,
post_id=post.id).delete()
def has_liked_post(self, post):
return PostLike.query.filter(
PostLike.users_id == self.id,
PostLike.post_id == post.id).count() > 0  
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), unique=True, nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
likes = db.relationship('PostLike', backref='post', lazy='dynamic')
comments = db.relationship('Comment', backref='title', lazy='dynamic')

def get_likers(self):
return PostLike.query.filter_by(users_id =User.id, post_id=self.id)

但当我点击模板中的viewLikes按钮时,它会给我一个错误,说明Function doesn't return any view

简单错误。在上一个方法中,您还没有返回render_template。return render_template('')

也可以在您的张贴对象上调用.first()

最新更新