我希望用户能够喜欢我的帖子,所以我在这里实现了。这是我的代码。它不会产生任何令人沮丧的错误。
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
url = models.URLField(max_length=250, blank=True, null=True)
views = models.IntegerField(default=0)
likes = models.ManyToManyField(User, related_name='likes')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
def total_likes(self):
return self.likes.count()
views.py
def like(request):
if request.method == 'POST':
user = request.user # bring login user
post_pk = request.POST.get('pk', None)
post = Post.objects.get(pk = post_pk) #bring the post object.
if post.likes.filter(id = user.id).exists(): #if exit
post.likes.remove(user) #likes deleted.
message = 'You disliked this'
else:
post.likes.add(user)
message = 'You liked this'
context = {'likes_count' : post.total_likes, 'message' : message}
return HttpResponse(json.dumps(context), content_type='application/json')
urls.py
urlpatterns = [
path('', PostListView.as_view(), name='community-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/<int:post_pk>/comment/new',views.comment_new, name='comment_new'),
path('post/<int:post_pk>/comment/<int:pk>/edit',views.comment_edit, name='comment_edit'),
path('post/<int:post_pk>/comment/<int:pk>/delete',views.comment_delete, name='comment_delete'),
path('like/', views.like, name='like'),
我的html
<input type="button" class="like" name="{{ memo.id }}" value="Like">
<p id="count{{ memo.id }}">count : {{ memo.total_likes }}</p>
<script type="text/javascript">
for(i = 0; i < $(".writer_name").length; i++){
if($("#user_name").text() == $(".writer_name")[i].innerHTML){
$("#control_id"+i).removeClass("hidden");
}
}
$('.like').click(function(){
var pk = $(this).attr('name')
$.ajax({
type: "POST",
url: "{% url 'like' %}",
data: {'pk': pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response){
id = $(this).attr('name')
$('#count'+ pk).html("count : "+ response.likes_count);
alert(response.message);
alert("likes :" + response.likes_count);
},
error:function(request,status,error){
alert("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}
});
})
</script>
我不确定我的ajax错误还是python错误。但对我而言,这里的逻辑是合理的。如果有人能说出问题所在,我将不胜感激。谢谢
答案 0 :(得分:0)
def like(request):
response_json = request.POST
response_json = json.dumps(response_json)
data = json.loads(response_json)
post = Post.objects.get(pk =data['pk'])
if post.likes.filter(id = user.id).exists(): #if exit
post.likes.remove(user) #likes deleted.
message = 'You disliked this'
else:
post.likes.add(user)
message = 'You liked this'
context = {'likes_count' : post.total_likes, 'message' : message}
return JsonResponse(context, safe=False)
尝试这样。您正在发送JSON数据类型,因此python必须如此解释。
答案 1 :(得分:0)
您正在使用jquery,在使用它之前,必须将代码包装在其中:
$(document).ready(()=>{
...
});