I am trying to build a single page app but like twitter for cs50 web project using Django
I am using fetch API to get the all the posts on the site and use javascript to plug them in like this :
document.querySelector('#all-posts-view').innerHTML = '';
fetch(`all_posts`,{
headers: new Headers({ 'secure': 'secure'})
})
.then(response => response.json())
.then(posts => {
console.log(posts)
posts.forEach(function(post) {
let div = document.createElement("div");
div.setAttribute('id', 'post');
console.log(post.author)
div.innerHTML = ` <a href='profile/${post.author}' id='profile-page' data-profile=${post.author_id} data-name=${post.author} > <P>${post.timestamp}</p> <h1 class="capitalize">${post.author}</h1></a> <h3>${post.post}</h3> <p>${post.likes}</p> <button onclick='style.color = "blue"'>Likes</button> {%if ${post.author} == 'zero'%} zzz{%endif%}`
document.querySelector("#all-posts-view").append(div);
})
})
and each div
has a button to like the post , but when the user click on the button and the likes go up by one I do not know how can I show to that user that the like button was clicked because if the page is refreshed the function will just show normal posts and the user will not be able to tell if he actually liked the post or not
After refreshing: After refreshing:
So how can I keep the button clicked to that user ? do I need a global variable to represent the user? or is my approach is wrong in the first place?
this is my views.py to that function :
def all_posts(request):
posts = Post.objects.all()
posts = posts.order_by("-timestamp").all()
return JsonResponse([post.serialize() for post in posts], safe=False)