我曾尝试实现Like(对于不喜欢的用户)和Dislike(对于已经喜欢该帖子的用户)按钮,但是我无法实现它。我尝试查看过去的问题,但无法解决问题。如果有人以前这样做过,请提供帮助。
我的Post机型的blog / models.py
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
likes = models.ManyToManyField(User, related_name='likes', blank=True)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def total_likes(self):
return self.likes.count()
我的博客/views.py
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
is_liked = False
if post.likes.filter(id=request.user.id).exists():
is_liked = True
return render(request, 'blog/post_detail.html', {'post': post, 'is_liked': is_liked, 'total_likes': post.total_likes(), })
def like_post(request):
post = get_object_or_404(Post, id=request.POST.get('id'))
is_liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
is_liked = False
else:
post.likes.add(request.user)
is_liked = True
context = {
'post': post,
'is_liked': is_liked,
'total_likes': post.total_likes(),
}
if request.is_ajax():
html = render_to_string('blog/like_section.html', context, request=request)
return JsonResponse({'form': html})
我的HTML和AJAX代码(此部分位于post_detail.html中)
<div id="like-section">
{% include 'blog/like_section.html' %}
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascirpt">
$('#like').click(function(){
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: "like_post",
data: {
'id':pk,
},
success: function(response){
$('#like-section').html(response['form'])
},
});
});
</script>
like-section.html是一个单独的模板:-
<p>{{ total_likes }} Like{{ total_likes|pluralize }}</p>
{% if request.user.is_authenticated %}
<form action="{% url 'like_post' %}" method="post">
{% csrf_token %}
{% if is_liked %}
<button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-danger">Dislike</button>
{% else %}
<button type="submit" id="like" name="post_id" value="{{ post.id }}" class="btn btn-primary">Like</button>
{% endif %}
</form>
{% endif %}
我的主项目文件夹urls.py代码:-
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/login/', auth_views.LoginView.as_view(), name='login'),
path('accounts/logout/', auth_views.LogoutView.as_view(next_page='/'), name='logout'),
path('', include('blog.urls')),
]
我的博客应用程序的urls.py代码:-
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
path('post/new/', views.post_new, name='post_new'),
path('post/<int:pk>/edit/', views.post_edit, name='post_edit'),
path('drafts/', views.post_draft_list, name='post_draft_list'),
path('post/<pk>/publish/', views.post_publish, name='post_publish'),
path('post/<pk>/remove/', views.post_remove, name='post_remove'),
path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'),
path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'),
path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'),
path('like/', views.like_post, name="like_post"),
]
正确的AJAX代码是
$(document).ready(function(event){
$(document).on('click', '#like', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: '{% url "like_post" %}',
data: {
'id': pk,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
success: function(response){
$('#like-section').html(response['form'])
},
error: function(rs, e){
console.log(rs.responseText);
},
});
});
});