一、前言
对于每篇博客,添加收藏
二、urls.py
url(r'^collect/$', views.collect),
三、views.py
@csrf_exempt
def collect(request):
if request.method == "POST":
blog_id = request.POST.get('article_id')
name = request.session.get('user_name')
name_id = str(BlogUser.objects.get(name=name).id)
# thisarticle = get_object_or_404(Articles, id=blog_id)
# thisarticle.increase_views()
data = {}
if BlogUserCollect.objects.filter(blogid=blog_id).count() >= 1:
data["result"] = "fail"
else:
obj = BlogUserCollect(blogid=blog_id,userid=name_id)
obj.save()
data["result"] = "success"
return HttpResponse(json.dumps(data), content_type='application/json')
四、html
<style type="text/css">
/*div通用样式*/
#collect{
background: #f5ab35;
color:white;
overflow: hidden;
z-index: 9999;
position: fixed;
padding:5px;
text-align:center;
width: 50px;
height: 50px;
font-size: 18px;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
/*右上角*/
div.right_top{
right: 20px;
top: 300px;
}
</style>
{% if collect_flag == 0 %}
<div id="collect" class="right_top"><span type="submit" class="iconfont icon-shoucang" style="text-align: center" onclick="collect()"></span></div>
{% else %}
<div id="collect" class="right_top"><span type="submit" class="iconfont icon-shoucang-copy" style="text-align: center;color: red" onclick="collect()"></span></div>
{% endif %}
<script type="text/javascript">
function collect(){
var article_id = {{ blog_list.id }};
console.log(article_id);
$.ajax({
url:"/JiaBlog/collect/",
type:'POST',
data:{
csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(),
article_id:article_id,
},
success:function (result) {
if(result.result=="fail" ){
swal(
'你已经收藏过啦!',
);}
else{
swal(
'收藏成功!',
);}
}
});
}
</script>