如何在喜欢之后立即制作不喜欢的按钮,反之亦然?在Django

时间:2017-04-20 03:50:44

标签: javascript jquery python django

我已经成功创建了一个相似的按钮,如果我喜欢一个帖子,计数器会增加并且它不会立即显示不同的按钮,我必须刷新页面才能显示它,甚至在刷新之后就像说,而不是不同,但如果我点击它会减少计数,即不喜欢它。

那么如何在喜欢之后立即制作不喜欢的按钮,反之亦然?谢谢。

以下是代码:

models.py

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True,null=True)
    likes = models.IntegerField(default=0)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

views.py

def like_post(request):
    liked = False
    if request.method == 'GET':
        post_id = request.GET['post_id']
        post = Post.objects.get(id=int(post_id))
        if request.session.get('has_liked_'+post_id, liked):
            print("unlike")
            if post.likes > 0:
                likes = post.likes - 1
                try:
                    del request.session['has_liked_'+post_id]
                except KeyError:
                    print("keyerror")
        else:
            print("like")
            request.session['has_liked_'+post_id] = True
            likes = post.likes + 1
    post.likes = likes
    post.save()
    return HttpResponse(likes, liked)

def post_detail(request, pk):
    post = get_object_or_404(Post, pk=pk)
    Post.objects.get(pk=pk)
    post_id = post.pk
    liked = False
    if request.session.get('has_liked_' + str(post_id), liked):
        liked = True
        print("liked {}_{}".format(liked, post_id))
    context = {'post': post, 'liked': liked}
    return render(request, 'blog/post_detail.html', {'post': post})

urls.py

url(r'like_post/$', views.like_post, name='like_post'),

Ajax的blog.js

$('#likes').click(function(){
    var postid;
    postid= $(this).attr("data-post_id");
    $.get('/blog/like_post/', {post_id: postid}, function(data){
               $('#like_count').html(data);
               $('#likes').hide();
    });
});

post_detail.html

<p>
    <strong id="like_count">{{ post.likes }}</strong> people like this category

{% if user.is_authenticated %}
    <button id="likes" data-post_id="{{post.id}}"  class="btn btn-primary" type="button">
    {% if liked %}
        <span class="glyphicon glyphicon-thumbs-down"></span>
        Unlike
        </button>
    {% else %}
        <span class="glyphicon glyphicon-thumbs-up"></span>
        Like
        </button>
    {% endif %}
{% endif %}
</p>

2 个答案:

答案 0 :(得分:1)

$('#likes').click(function(){
    $('.like_span').toggleClass('glyphicon-thumbs-down glyphicon-thumbs-up');
    var postid;
    postid= $(this).attr("data-post_id");
    $.get('/blog/like_post/', {post_id: postid, liked:$('.like_span').hasClass('glyphicon-thumbs-up')}, function(data){
               $('#like_count').html(data);
               $('#likes').hide();
    });
});

然后添加课程like_span

<span class="like_span glyphicon glyphicon-thumbs-up"></span>
<span class="like_span glyphicon glyphicon-thumbs-down"></span>

然后在视图中,您将获得request.GET['liked']为真或假。为增加和减少提供该值

答案 1 :(得分:0)

处理的一个好方法是当用户点击喜欢或不喜欢时刷新页面。

相反,请jquery ajax使用rest api(DRF) 增加减少类似计数。

使用jquery切换图标而不是django模板标记条件{% if liked %}