天天看点

收藏功能的实现

1.在urls.py文件里面添加:

# 用户收藏
url(r'^add_fav/$',AddFavView.as_view(),name='add_fav'),

2.在views里面      
# 用户收藏 和取消收藏
class AddFavView(View):
    def post(self,request):
        fav_id = request.POST.get('fav_id',0)
        fav_type = request.POST.get('fav_type',0)

        if not request.user.is_authenticated():
            # 判断用户是否登陆

            return HttpResponse('{"status":"fail", "msg":"用户未登录"}', content_type='application/json')
        exist_records = UserFavorite.objects.filter(user=request.user, fav_id=int(fav_id), fav_type=int(fav_type))
        if exist_records:
            #  如果记录已经存在,那么表示用户取消收藏
            exist_records.delete()

            if int(fav_type) == 1:
                course = Courses.objects.get(id=int(fav_id))
                course.fav_nums -= 1
                if course.fav_nums < 0:
                    course.fav_nums = 0
                course.save()
            elif int(fav_type) == 2:
                org = CourseOrg.objects.get(id=int(fav_id))
                org.fav_nums -= 1
                if org.fav_nums < 0:
                    org.fav_nums = 0
                org.save()
            elif int(fav_type) == 3:
                teacher = Teaher.objects.get(id=int(fav_id))
                teacher.fav_nums -= 1
                if teacher.fav_nums < 0:
                    teacher.fav_nums = 0
                teacher.save()


            return HttpResponse('{"status":"success", "msg":"收藏"}', content_type='application/json')
        else:
            user_fav = UserFavorite()
            if int(fav_id) > 0 and int(fav_type) > 0:
                user_fav.user = request.user
                user_fav.fav_id = int(fav_id)
                user_fav.fav_type = int(fav_type)
                user_fav.save()

                if int(fav_type) == 1:
                    course = Courses.objects.get(id=int(fav_id))
                    course.fav_nums += 1
                    course.save()
                elif int(fav_type) == 2:
                    org = CourseOrg.objects.get(id=int(fav_id))
                    org.fav_nums += 1
                    org.save()
                elif int(fav_type) == 3:
                    teacher = Teaher.objects.get(id=int(fav_id))
                    teacher.fav_nums += 1
                    teacher.save()


                return HttpResponse('{"status":"success", "msg":"已收藏"}', content_type='application/json')
            else:

                return HttpResponse('{"status":"fail", "msg":"收藏出错"}', content_type='application/json')


3.在HTML文件里面

      
function add_fav(current_elem, fav_id, fav_type){
    $.ajax({
        cache: false,
        type: "POST",
        url:"{% url 'org:add_fav' %}",
        data:{'fav_id':fav_id, 'fav_type':fav_type},
        async: true,
        beforeSend:function(xhr, settings){
            xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
{#            alert(11)#}
        },
        success: function(data) {
            alert(22)
            console.log(data);
            console.log(current_elem);
            if(data.status == 'fail'){
                if(data.msg == '用户未登录'){
                    window.location.href="/login/" target="_blank" rel="external nofollow" ;
                }else{
                    current_elem.text(data.msg)
                    alert(data.msg)
                }

            }else if(data.status == 'success'){
                current_elem.text(data.msg)
            }
        },
    });
}

$('.collectionbtn').on('click', function(){
    add_fav($(this), {{ course_org.id }}, 2);
});

$(function(){
    var $precision = $('.precision'),
        score = $precision.attr('data-star-scope'),
        option =  {
                    half      : true,
                    path      : '{% static '' %}images/',
                    precision  : true,
                    size      : 24,
                    starOff       : 'g_star.png',
                    starOn    : 'r_star.png',
                    starHalf   : 'h_star.png',
                    hints       : ['极差', '差', '一般', '好评', '非常满意'],
                    noRatedMsg  : '暂时还未获得评价!',
                    readOnly    : true,
                    score       : score
                };
    $precision.raty(option);

    $('.jsFavBtn').on('click', function(){
        var type = $(this).attr('data-fav-type');
        if(type == '1'){
            favPraise($(this), 'fav' ,1 , '收藏');

        }else if(type == '3'){
            favPraise($(this), 'fav' ,3 );

        }else if(type == '11'){
            favPraise($(this), 'pra', 1);

        }else if(type == '4'){
            favPraise($(this), 'fav' ,4 );

        }
    });
})
</script>      
{% if has_fav %}已收藏{% else %}收藏{% endif %}      

转载于:https://www.cnblogs.com/chenyang13677/p/7773933.html