【小白实战】利用django2.0,搭建属于自己的博客(21)


发布时间:2019-02-15 13:08    作者: Uncle Hui   已过去:1 年,4 月   阅读总量:355 已被赞:0


【通过ajax实现博客文章点赞】

1.在文章模型下,新增一个字段,存储点赞数

vote = models.IntegerField(default=0)

2.新建存储点赞的模型

#点赞模型
class Poll(models.Model):
    ip = models.CharField(max_length=100, null=True, blank=True)
    blog = models.ForeignKey(Post, on_delete=models.CASCADE)

    def __str__(self):
        return str(self.blog)

3.新建路由

path('zan/', vote, name='zan'),#点赞路由

4.建立点赞处理的视图和获取IP的函数

#创建获取点赞者IP的函数
def getIP(request):
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        return request.META['HTTP_X_FORWARDED_FOR']
    else:
        return request.META['REMOTE_ADDR']

#创健点赞处理视图
def vote(request):
    if request.method =='POST':
        ret={'status':1001,'error':''}
        post_id=request.POST.get('post_id')
        blog = Post.objects.get(id = post_id)
        ip = getIP(request)
        if Poll.objects.filter(ip=ip, blog=blog).exists():
            ret['error'] = '你已经点赞了,请不要重复点赞!'
            ret['numbers'] = blog.vote
            ret['status'] = 1001
        else:
            Poll.objects.create(ip=ip, blog=blog)
            blog.vote += 1
            blog.save()
            ret['numbers'] = blog.vote
            ret['status'] = 1002
        return  HttpResponse(json.dumps(ret))
    return render(request,'comments/ajax.html')

5.html写入点赞和ajax

<button type="button" class="btn btn-default btn-sm btn-danger">
    <span onclick="tijiao1()">赞</span>
</button>
<span id="status"></span>
<span id="vote-numbers"> 已被赞:{{ post.vote }}</span>

 

{#ajax处理点赞#}
<script>
    function tijiao1(){

        $.ajaxSetup({
            data:{csrfmiddlewaretoken:'{{ csrf_token }}'}, #令牌
        });
        $.ajax({
            url:'{% url 'zan' %}', #交给哪个路由
            type:'POST',
            data:{post_id:{{ post.id }}}, #要传去后台的键值队
            success:function(callback){
                var callback_dict = $.parseJSON(callback);  
                var vote_numbers = $('#vote-numbers');
                if (callback_dict.status==1002){
                    $('#status').text('谢谢点赞');
                    $('#status').removeClass('error').addClass('success'); 
                    vote_numbers.text('已点赞:' + callback_dict.numbers.toString()); #渲染点赞后的值
                }else if(callback_dict.status == 1001){
                    $('#status').text(callback_dict.error);
                    $('#status').removeClass('success').addClass('error');
                    vote_numbers.text('已点赞:' + callback_dict.numbers.toString());
                }
            }
        })
    }
</script>

 

点赞

0




登陆后方可评论