So I am trying to add a like button feature to my code that allows users to like specific posts. The likes will be linked to a logged in user and the number of likes will be shown. Implementing the front end won't be difficult but I am having a problem with the back end.
I am using this post here as a guide which does a follower system instead
This is what I have so far?
I have created a table for likes in models.py :
likers = db.Table('likers',
db.Column('liker_id', db.Integer, db.ForeignKey('post.id')),
db.Column('liked_id', db.Integer, db.ForeignKey('post.id'))
)
In my Models.py for my user class:
class User(db.Model, UserMixin):
#Code
liked = db.relationship(
'User', secondary=likers,
primaryjoin=(likers.c.liker_id == id),
secondaryjoin=(likers.c.liked_id == id),
backref = db.backref('likers', lazy='dynamic'), lazy='dynamic')
def like(self, post):
if not self.is_liking(post):
self.liked.append(post)
def unlike(self, post):
if self.is_liking(post):
self.liked.remove(post)
def is_liking(self, post):
return self.liked.filter(
likers.c.liked_id == post.id).count() > 0
In my routes.py for my users blueprint I have:
@users.route("/like/<int:post_id>")
@login_required
def like(post_id):
post = Post.query.get_or_404(post_id)
current_user.like(post)
db.session.commit()
flash('Post has been liked')
return redirect(url_for('posts.post', post_id=post.id))
@users.route("/unlike/<int:post_id>")
@login_required
def unlike(post_id):
post = Post.query.get_or_404(post_id)
current_user.unlike(post)
db.session.commit()
flash('Post has been unliked')
return redirect(url_for('posts.post', post_id=post.id))
What am I doing wrong? I keep getting errors such as:
builtins.KeyError
KeyError: 'likers'
I have done a comment section and I know the relationship for the likes will be similar to the comments but I am struggling to implement it. I am relatively new to flask and I have tried using the documentations but haven't found anything to help me...
This is my final hope.