I am trying to learn django and a bit more. Got a problem with counting number of likes for every post in tape. Problem is that I can not get id of post. If I refresh page, count of likes changes. But to make it changing with ajax is real problem. Please explain me how make changing likes count for every post in tape, if click like button.
Ajax code.
{% block jquery %}
function updatePostLikesCount(){
var postlikescount = $(".post-likes-count")
$.ajax({
type: "GET",
url: "/like_post/{{ post.id }}/post_likes_count/",
success: function(data){
postlikescount.html(data.count);
},
error: function(response, error){
}
})
}
$(".post-like").click(function(event){
var img = $(this);
event.preventDefault();
$.ajax({
url: img.parent().attr('href'),
success: function(){
updatePostLikesCount();
},
error: function(response, error){
}
})
});
{% endblock %}
Here is tape of posts.
{% for post in tape %}
...
{{ post.text }}
...
<a href="/like_post/{{ post.id }}/">
<img class="post-like" src="{% static "" %}"/>
</a>
<span class="post-likes-count" >
{{ post.like.liked_users.count }}
</span>
{% endfor %}
Here is a view that count post's likes
def post_likes_count(request, post_id, *args, **kwargs):
if request.is_ajax():
like = Like.objects.get(post_id=post_id)
if like.liked_users.count == None:
count = 0
else:
count = LikeTimestamp.objects.filter(like_id=like.id).count()
return JsonResponse({
'count': count,
})
else:
raise Http404
Else I tried to reload an element of page with likes , but was defeated :-)
Some ways to improve this.
First ... you always want the html for the count to exist and should only hide it if there are no likes or show as zero. Otherwise you would need to add the html with javascript when first like is voted
Next
This will include all elements with that class in the page .... not the specific one you want when you click the button.
Instead you could pass the one you want into
updatePostLikesCount()
as an argumentChange
to
And in the click handler modify so we pass in the appropriate element
Updated:
Change the view slightly like this(adding data-id):