Issue
I am almost done with my project, I completed every step and now I am stuck at the very least, I am not able to show the like count per post in my project.
views.py
def index(request):
posts = Post.objects.all().order_by("date").reverse()
paginator = Paginator(posts, 10)
number = request.GET.get('page')
currentPosts = paginator.get_page(number)
likeList = []
try:
for like in likes:
if like.userLiking.id == request.user.id:
likeList.append(like.postLiked.id)
except:
likeList = []
return render(request, "network/index.html", {
"currentPosts": currentPosts
})
index.js
function like(id, likeList) {
if (likeList.indexOf(id) >= 0) {
fetch(`/remove/${id}`)
.then(response => response.json())
.then(result => {
console.log(result),
window.location.reload()
})
} else {
fetch(`/add/${id}`)
.then(response => response.json())
.then(result => {
console.log(result),
window.location.reload()
})
}
}
index.html
<div>
<ul style="list-style: none">
{% for post in currentPosts %}
<li><a href="{% url 'profile' post.user.id %}"> From: {{ post.user }}</a></li>
<li><h5 id="description{{ post.id }}">{{ post.description }}</h5></li>
<li>{{ post.date }}</li>
{% if user.is_authenticated and user == post.user %}
<button id="editButton{{ post.id }}" onclick="edit({{ post.id }})">Edit</button><br>
<div id="text{{ post.id }}"></div>
<div id="save{{ post.id }}"></div>
{% endif %}
{% if user.is_authenticated %}
{% if post.id not in likeList %}
<button class="likebtn" id="{{ post.id }}" onclick="like({{ post.id }}, {{ likeList }})">Like</button><br>
{% else %}
<button class="unlikebtn" id="{{ post.id }}" onclick="like({{ post.id }}, {{ likeList }})">Unlike</button><br>
{% endif %}
{% endif %}
<p id="likeCount{{ post.id }}">Likes: </p>
----------------------------------
{% endfor %}
</ul>
</div>
models.py
class Like(models.Model):
userLiking = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userLiking")
postLiked = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="postLiked")
def __str__(self):
return f"{self.userLiking} liked {self.postLiked}"
I tried: post = Post.objects.get(id=id) - but index does not take id as an argument.
Solution
You can annotate a count to each item in your queryset:
from django.db.models import Count
posts = Post.objects.annotate(likes=Count("postLiked")).order_by("date").reverse()
Then you can simply access it in the template via {{ object.likes }}
. Rename the object name as required.
Read more in the Django documentation about Generating aggregates for each item in a QuerySet.
Answered By - Marco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.