I'm making it save the colour in localStorage to see a red heart if liked and no colour if disliked after refreshing the web page. But I don't understand why it is not shown. I have debugged and the localSotage values are correct.
Index.js
const color = ["#000000", "#FF0000"];
let colorIndex = parseInt(localStorage.getItem("colorIndex")) || 0;
console.log("Initial: " + colorIndex);
function like(elem) {
const postId = elem.attributes["data-id"].value
const csrftoken = getCookie('csrftoken');
fetch(`like/${postId}`, {
method: 'POST',
headers: { 'X-CSRFToken': csrftoken },
mode: 'same-origin'
}).then(res => res.json())
.then(data => {
document.getElementById(postId).innerText = data.numLikes
console.log(data.liked + ", color: " + color[data.numLikes - 1]);
if (data.liked == true) {
colorIndex = data.isLiked;
document.getElementById(`icon-${postId}`).setAttribute("fill", color[colorIndex]);
console.log("liked == true " + colorIndex);
} else if (data.liked == false) {
colorIndex = data.isLiked;
document.getElementById(`icon-${postId}`).setAttribute("fill", color[colorIndex]);
console.log("liked == false " + colorIndex);
}
localStorage.setItem("colorIndex", colorIndex);
})
}
views.py
if request.method == "POST":
postId = Post.objects.get(id = id) # Almacena los id de cada post
if not postId.likes.filter(id = request.user.id).exists(): # Si no existe un like por el usuario
newStatus = True
isLiked = 1
postId.likes.add(request.user) # Añadelo
postId.save()
else:
newStatus = False
isLiked = 0
postId.likes.remove(request.user) # Si no lo quitas
postId.save()
return JsonResponse({"liked": newStatus, "isLiked": isLiked, "id": id, "numLikes": postId.likes.count()},status=200)
return JsonResponse({"message": "Wrong method"}, status=400)
You might have a syntax problem with your attribute setting.
Try:
setAttribute("style", "fill:" + color[colorIndex])
Bear in mind this may override any other style properties you don't include, so you can avoid that by settting fill directly:
document.getElementById(`icon-${postId}`).style.fill = color[colorIndex]
The other thing that might be causing you trouble is the fill is only being set in the like() function, presumably responding to clicking a like button of some sort. If the page is reloaded, there is nothing in the code shown that will test to see if the post has been liked - the colour set in the like() function won't persist after a page reload as it hasn't been called.
The best way to handle this is in the django template itself, seeing as you are storing the 'liked' data in the database. First, in your view, get a list of liked posts
In this example, 'likes' is a recordset passed to your template from your view - I'm assuming Likes is a ManyToMany field linking users to posts:
user_likes = Likes.objects.filter(id = request.user.id)
You can make the filter more specific for efficiency based on the page's requirements. Pass the result of this filter to the template via context.
When you come to display the post do something like:
<div class="post">
...
<img id="icon-{{post.id}}" class="
{% if post in user_likes %}
liked
{% else %}
notliked
{% endif %}
">
</div>
And have your classes defined in your CSS to include your fill values eg,
.liked {
fill:#FF0000
}
.notliked {
fill:#000000
}
This will handle your coloring without having to make any ajax type javascript calls