I am all new to javascript. I am making a like button that will increase the number of likes of a post asynchronously without reloading the whole page. Following is my Django views function.
views.py
@login_required
def likepost(request,id):
post = NewPost.objects.get(id = id)
is_like = False
for like in post.likepost.all():
if like == request.user and request.method == "POST":
is_like = True
break
if not is_like:
post.likepost.add(request.user)
else:
post.likepost.remove(request.user)
return JsonResponse({
"id" : id,
"is_like" : is_like,
"num_like" : post.likepost.count()
})
Here id is the primary key of NewPost model. My javascript will fetch an API using this id variable. Here is my js function.
document.addEventListener("DOMContentLoaded",function(){
document.querySelector('#like').addEventListener('click', ()=> like_function());
})
function like_function(){
fetch(`index/${id}/like`)
.then(response => response.json())
.then(result => {
if(result.is_like){
document.querySelector('#like').innerHTML = "Like";
}
else{
document.querySelector('#like').innerHTML = "Unlike";
}
})
}
<button onclick="like_function()" id = "like" class="btn btn-link"><i class="fa fa-heart"></i> </button>
<small id="num_of_likes">{{ posts.likepost.all.count }}</small>
{% block script %}
<script src="{% static 'network/controller.js' %}"></script>
{% endblock %}
<button class="btn btn-link" style="text-decoration: none;">Comment</button>
<a href="{% url 'postpage' id=posts.id %}" class="btn btn-link" style="text-decoration: none;">View Post</a>
Here, I've shared my javascript function as well as my HTML template.
If I click the like button following message appears.

What should I do now?
You need to add the item primary key in the like_function call:
<button onclick="like_function({{ posts.pk }})" id = "like" class="btn btn-link"><i class="fa fa-heart"></i> </button>
then you define the like_function as:
function like_function(id) {
fetch(`index/${id}/like`)
.then(response => response.json())
.then(result => {
if(result.is_like){
document.querySelector('#like').innerHTML = "Like";
}
else{
document.querySelector('#like').innerHTML = "Unlike";
}
})
}