I'm new at Ajax and Django. I have an Ajax like button that adds "likes" to my database. Besides the button, my template also displays the total number of likes. The button works but I can't figure out how to update the "like-count" div because calling {{ post.likes.count }}
displays the old result. I'm guessing that's due to caching? To get around this I declared a like_count variable in my view and then add +=1 when liked.
How do I make {{ like_count }}
work in my template? Using
return render(request, 'app/blog.html', {'like_count': like_count})
sends me to blank page instead of updating the div.
View:
@login_required
def like(request):
if request.is_ajax():
user = request.user
post_id = request.POST.get('post', None)
content = ContentType.objects.get_for_model(Post)
like_count = Like.objects.filter(content_type=content, object_id=post_id).count()
if Like.objects.filter(user=user, content_type=content, object_id=post_id).exists():
# remove like
Like.objects.filter(user=user, content_type=content, object_id=post_id).delete()
like_count -=1
else:
# add a new like
Like.objects.create(user=user, content_type=content, object_id=post_id)
like_count +=1
return HttpResponse()
return render(request, 'app/blog.html', {'like_count': like_count})
Template:
<div id="like-count">Like {{ post.likes.count }}</div>
<form method="post" action="{% url 'like' %}" id="like-form">
{% csrf_token %}
<input type="hidden" id="post_id" name="post" class="hidden_id" value="{{ post.pk }}" />
<input type="hidden" id="user_id" name="user" class="hidden_id" value="{{ user.pk }}" />
<button class="btn">Like</button>
</form>
<script type="text/javascript">
var frm{{ post.id }} = $('#like-form');
frm{{ like.id }}.submit(function (ev) {
$.ajax({
type: frm{{ post.id }}.attr('method'),
url: frm{{ post.id }}.attr('action'),
data: frm{{ post.id }}.serialize(),
success: function (data) {
document.getElementById("like-count").innerHTML = {{ like_count }};
}
});
ev.preventDefault();
});
</script>