天天看點

收藏功能的實作

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