Issue
This is my models.py and index.html and views.py I tried the above and I am expecting to get total like count in my index page but i am only getting 0 likes why is that happening. And how do I fix it.
`from django.contrib.auth.models import AbstractUser
from django.db import models
from datetime import datetime
from django.contrib.auth import get_user_model
class CustomUser(AbstractUser):
profile_picture = models.ImageField(
upload_to="profile_pics/", blank=True, null=True
)
# Add any other custom fields as needed
def __str__(self):
return self.username
class Post(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
title = models.CharField(max_length=1000)
content = models.TextField()
created_at = models.DateTimeField(default=datetime.now, null=True, blank=True)
likes = models.ManyToManyField(
get_user_model(), related_name="liked_posts", blank=True
)
class Like(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
def __str__(self):
return f"{self.user.username} likes {self.post.title}"`
and this is my index.html
`{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<h2>Welcome to the Home Page!</h2>
{% for post in posts %}
<!-- Display post details as needed -->
<div>
<h3>{{ post.title }}</h3>
<small>{{post.created_at}}</small>
<p>{{ post.content }}</p>
<form id="likeForm{{ post.id }}" data-post-id="{{ post.id }}" method="post">
{% csrf_token %}
<input type="submit" value="Like post">
<span id="likeCount{{ post.id }}">{{ post.likes.count }}</span> Likes
</form>
</div>
{% endfor %}
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(document).ready(function () {
$('form[id^="likeForm"]').submit(function (event) {
event.preventDefault(); // Prevent the default form submission
var postID = $(this).data('post-id');
// Send an AJAX request to the server
$.ajax({
type: 'POST',
url: '/like/',
data: {
'post_id': postID,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
success: function (data) {
// Update the like count on success
$('#likeCount' + postID).text(data.likes);
},
error: function (error) {
console.log('Error:', error);
}
});
});
});
</script>
{% endblock %}`
and my views.py
`from django.shortcuts import render, redirect
from .forms import SignUpForm
from django.contrib import messages
from .models import Post, Like
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
# Create your views here.
def index(request):
posts = Post.objects.all()
return render(request, "index.html", {"posts": posts})
def register(request):
if request.method == "POST":
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data["username"]
messages.success(request, f"{username} has been registered")
return redirect("index")
form = SignUpForm()
return render(request, "register.html", {"form": form})
def create(request):
if request.method == "POST":
title = request.POST.get("title")
content = request.POST.get("content")
user = request.user
new_post = Post.objects.create(title=title, content=content, user=user)
new_post.save()
posts = Post.objects.all()
return redirect("index")
return render(request, "create.html")
def like_post(request):
if request.method == "POST":
post_id = request.POST.get("post_id")
post = get_object_or_404(Post, id=post_id)
user = request.user
# Check if the user has already liked the post
if Like.objects.filter(user=user, post=post).exists():
return JsonResponse(
{"error": "You have already liked this post"}, status=400
)
# Create a new like
like = Like(user=user, post=post)
like.save()
print(Like.objects.filter(post=post).count())
# Return the updated like count as JSON
updated_likes_count = Like.objects.filter(post=post).count()
print(updated_likes_count)
print("n")
return JsonResponse({"likes": updated_likes_count})
else:
return JsonResponse({"error": "Invalid request"}, status=400)`
I tried the above and I am expecting to get total like count in my index page but i am only getting 0 likes why is that happening. And how do I fix it It is not letting me post so i am adding some extra words .................mkefekjafjdakfkfkjf lorem ipsum wejldskjdskdkjdjj
JJ J J J J J
J WHYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY.
Solution
Ok.
1) Remove
likes = models.ManyToManyField( get_user_model(), related_name="liked_posts", blank=True )
part from Post model.
2) add
@property
def post_like_count(self):
count = Like.objects.filter(post=self).count()
return count
after your
def __str__(self):
function. Inside Post model.
- Inside templates use
{{ post.post_like_count }}
Answered By - Pycm
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.