【发布时间】:2020-05-01 12:19:00
【问题描述】:
我正在开发一个网站,用户可以在该网站上点赞帖子,并且我的主页上有所有用户帖子的列表。
我正在使用 Ajax 来防止在单击赞按钮时重新加载页面。我能够实现类似的视图,但我有一个问题。 Ajax 工作正常,但只有第一篇文章中的“赞”按钮在单击时会发生变化,从“赞”变为“不赞”。第二篇文章中的“赞”按钮没有改变。
我的代码如下:
@login_required
def home_view(request):
#All posts in new feed
all_images = Post.objects.filter(
Q(poster_profile=request.user, active=True)|
Q(poster_profile__from_user__to_user=request.user, active=True)|
Q(poster_profile__to_user__from_user=request.user, active=True)|
Q(poster_profile__profile__friends__user=request.user, active=True))
#If post is liked displayed button
posts = Post.objects.filter(pk__in=all_images)
is_liked = {}
for post in posts:
if post.likes.filter(id=request.user.id).exists():
is_liked[post.id] = True
context = {'all_images': all_images, 'is_liked': is_liked}
return render(request,'home.html', context)
#Post likes
@login_required
def like_post_view(request):
# post = get_object_or_404(Post, id=request.POST.get('post_id'))
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:
is_liked = True
post.likes.add(request.user)
context = {'post': post, 'is_liked': is_liked,}
if request.is_ajax():
html = render_to_string('ajax_postlikes.html', context, request=request)
return JsonResponse({'form': html})
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
模板:ajax_postlike.html
<p>Like{{post.likes.count}}</p>
<form action="{% url 'site:like_post' %}" method="POST">
{% csrf_token %}
{% if is_liked %}
<button type="submit" name="post_id" value="{{ post.id }}" class="like float-left mr-2">
Unlike
</button>
{% else %}
<button type="submit" name="post_id" value="{{ post.id }}" class="like float-left mr-2">
like
</button>
{% endif %}
</form>
模板:home.html
<div class="ml-1" id="like-section">
{% include 'ajax_postlikes.html' %}
</div>
Ajax/Jquery:
<script type="text/javascript">
$(document).on('click', '.like', function(event){
event.preventDefault();
var pk = $(this).attr('value');
$.ajax({
type: 'POST',
url: "{% url 'site:like_post' %}",
data: {'id':pk, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: 'json',
success: function(response) {
$('#like-section{{ post.id }}').html(response['form'])
console.log($('#like-section{{ post.id }}').html(response['form']));
},
error: function(rs, e) {
console.log(rs.resopnseText);
},
});
});
</script>
我需要做些什么来解决在单击事件后按钮状态不在“喜欢”和“不喜欢”之间切换的问题?
[![在此处输入图片描述][1]][1][1]:https://i.stack.imgur.com/X4MWc.jpg
【问题讨论】: