So I was changing some variable names when working on my website made using flask and after I was done changing the variable names, I found out that my like button is no longer working as intended. I click on it to like a post and then it does not update the like counter which is supposed to display the number of likes a post has. I refresh the page and the like counter is updated. It stays that way and shows that I have liked the post whenever I refresh the page too. I unlike the post and refresh it again, then it shows that the like has been removed, it does not update automatically. The tutorial I was following suggested to empty my cache and hard reload but that did not seem to work either. The whole thing was working fine before I changed the variable names so that might have something to do with it. The like button and counter exist inside the read route so I thought I should include that as well.
Here are the relevant routes in question:
@app.route('/read/<post_name>')
def read(post_name):
posts = Image.query.filter_by(post_name=post_name)
post1=Image.query.filter_by(post_name=post_name).first()
post = Posts.query.filter_by(id=post1.post_id).first()
author_id =Image.query.filter_by(post_name=post_name).first().user_id
author = User.query.filter_by(id=author_id).first()
return render_template('readmanga.html', posts=posts, post=post, post1=post1, user=current_user, author=author, post_name=post_name)
@app.route('/like-post/<post_id>', methods=["POST","GET"])
@login_required
def like(post_id):
post = Posts.query.filter_by(id=post_id).first()
like = Like.query.filter_by(author=current_user.id, post_id=post.id).first()
if not post:
return jsonify({'error':'Post does not exist.'}, 400)
elif like:
db.session.delete(like)
db.session.commit()
else:
like = Like(author=current_user.id,
post_id=post.id
)
db.session.add(like)
db.session.commit()
return jsonify({'likes':len(post.likes), 'liked':current_user.id in map(lambda x: x.author, post.likes)})
Here is the relevant database model:
class Posts(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
# post_name = db.Column(db.String(50), nullable=False)
likes = db.relationship('Like', backref='Posts', passive_deletes=True)
date_created = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now(tz=datetime.timezone.utc))
comments = db.relationship('Comment', backref='Posts', passive_deletes=True)
class Like(db.Model):
id = db.Column(db.Integer, primary_key=True)
author = db.Column(db.Integer, db.ForeignKey('user.id', ondelete="CASCADE"), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('posts.id', ), nullable=False)
Here is the template:
<div style="display: flex; flex-direction:column; justify-content: center; align-items: center; margin-top: 1.75%;">
{% set post_id = post.id | string() %}
{% set link = "/like-post/"+post_id %}
{% if user.id in post.likes|map(attribute="author")|list %}
<i class="fa fa-thumbs-up" id="likebtn-{{ post.id }}" style="font-size: 48px; color: cornflowerblue" onclick="like('{{ post.id }}')"></i>
{% else %}
{% if user.id in post.likes|map(attribute="author")|list %}
<i class="fa fa-thumbs-up" id="likebtn-{{ post.id }}" style="font-size: 48px; color: cornflowerblue" onclick="like('{{ post.id }}')"></i>
{% else %}
{% if current_user.is_authenticated %}
<i class="fa fa-thumbs-up" id="likebtn-{{ post.id }}" style="font-size: 48px; color: white" onclick="like('{{ post.id }}')"></i>
{% else %}
<span id="message" style="font-family: sans-serif; font-weight: bold;"></span>
<i class="fa fa-thumbs-up" id="likebtn-{{ post.id }}" style="font-size: 48px; color: white" onclick="displayMessage('You need to log in to like posts.')"></i>
{% endif %}
{% endif %}
{% endif %}
<span id="likes-count-{{ post.post_id }}" style="font-family: sans-serif; font-weight: bold; color: white;">{{post.likes|length}}</span>
</div>
<script type="text/javascript" src="{{ url_for('static', filename='read.js') }}">
</script>
Here is the javascript code:
function like(postID) {
const likeCount = document.getElementById(`likes-count-${postID}`);
const likeButton = document.getElementById(`likebtn-${postID}`);
fetch(`/like-post/${postID}`, { method: "POST"})
.then((res) => res.json())
.then((data) => {
console.log(data)
likeCount.innerHTML = data['likes'];
if (data['liked'] === true) {
likeButton.style.color = 'cornflowerblue';
} else {
likeButton.style.color = 'white';
}
}).catch((e) => console.log(e));
}
Please help me as I am not able to find the error in this code and it is practically the same as my code before that was working, just with different variable dependencies.