How do i implement a like button function to posts in Python Flask?
class User(UserMixin, db.Model):
# Code
liked = db.relationship(
'PostLike',
foreign_keys='PostLike.user_id',
backref='user', lazy='dynamic')
def like_post(self, post):
if not self.has_liked_post(post):
like = PostLike(user_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(
user_id=self.id,
post_id=post.id).delete()
def has_liked_post(self, post):
return PostLike.query.filter(
PostLike.user_id == self.id,
PostLike.post_id == post.id).count() > 0
class PostLike(db.Model):
__tablename__ = 'post_like'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
post_id = db.Column(db.Integer, db.ForeignKey('post.id'))
@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)
Then when you're listing your posts, set your anchors something like this:
{% for post in posts %}
{% if current_user.has_liked_post(post) %}
<a href="{{ url_for('like_action', post_id=post.id, action='unlike') }}">Unlike</a>
{% else %}
<a href="{{ url_for('like_action', post_id=post.id, action='like') }}">Like</a>
{% endif %}
{% endfor %}
Let's assume your Post
model looks something like this:
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.Text)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
recipient_id = db.Column(db.Integer, db.ForeignKey('user.id'))
likes = db.relationship('PostLike', backref='post', lazy='dynamic')
You'd use:
p = Post.query.filter_by(id=1).first()
p.likes.count()
Or, you'd use this in your .html file:
{% for post in posts %}
{% if current_user.has_liked_post(post) %}
<a href="{{ url_for('like_action', post_id=post.id, action='unlike') }}">Unlike</a>
{% else %}
<a href="{{ url_for('like_action', post_id=post.id, action='like') }}">Like</a>
{% endif %}
{{ post.likes.count() }} likes
{% endfor %}