一、点赞与点灭
思路分析:
1、给点赞和点灭添加事件
2、发送ajax请求
3、实现点灭的时候需要在给表里面增加一个字段,不用再创建一张表来存储了
注意点赞和点灭。评论等涉及到的一个知识点:
事务:要么同时发生,要么同时不发生(就像你到银行里面取钱一样,你输了200,而取款机却把你的钱扣了,不给你钱。那你就不高兴了)
所以,当用户进行点赞的时候,创建赞示例和点赞数必须是同时发生的,当你点完一次赞,数据库里的赞和点赞数都是要增加的。这就用到事务了。
说起事务,在sql里面学过,那么怎么在django中实现事务呢?
1、首先需要导入:
from django.db import transaction
2、如下
with transaction.atomic(): print("========") # 当有人点赞的时候数据库的数据肯定会多一条 models.Article_poll.objects.create(user_id=user_id,article_id=article_id) # 并且点赞数加1 models.Article.objects.filter(id=article_id).update(up_count=F("up_count")+1)
下面是实现点赞和点灭的具体操作
class Article_poll(models.Model): '''文章点赞表''' time = models.DateTimeField(verbose_name="点赞时间",auto_now_add=True) article = models.ForeignKey(to="Article",verbose_name="点赞文章",null=True,blank=True) #一个文章可以有多个赞 user = models.ForeignKey(to="UserInfo",verbose_name="点赞人",null=True,blank=True) is_positive = models.BooleanField(default=1,verbose_name="点赞或踩") #如果为True的时候代表式赞,如果是False的时候代表式
//用ajax实现点赞 $(".diggit").click(function () { if ($(".info").attr("user_name")) { //登录状态 $.ajax({ url: "/blog/poll/", type: "POST", data: { csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(), article_id: "{{ article_obj.id }}", //需要知道用户对那篇文章点赞 is_positive: "1" }, success: function (data) { var data = JSON.parse(data); console.log(data["tishi"]); //falseif (data["state"]) { var val = parseInt($("#digg_count").html()) + 1; $("#digg_count").html(val); $(".message").html("点赞成功").css("color", "red"); } else if (data["is_repeat"]) { $(".message").html("不能重复点赞").css("color", "red") } } }) } else { alert(location.pathname); //拿到的是路径部分 location.href = "/login/?next=" + location.pathname } });
点灭
1 //用ajax实现点灭 2 $(".buryit").click(function () { 3 if ($.cookie("username")) { //登录状态,和点赞一样,是第二种方式,建议用cookie的方式 4 $.ajax({ 5 url: "/blog/poll/", 6 type: "POST", 7 headers: {"X-CSRFToken": $.cookie('csrftoken')}, 8 data: { 9 csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").val(), 10 article_id: "{{ article_obj.id }}", 11 is_positive: "0" 12 }, 13 success: function (data) { 14 var data = JSON.parse(data); 15 console.log(data); 16 console.log(data.tishi); 17 if (data["state"]) { 18 var val = parseInt($("#bury_count").html()) + 1; 19 $("#bury_count").html(val); 20 $(".message").html("踩成功").css("color", "red"); 21 } 22 else if (data["is_repeat"]) { 23 $(".message").html("不能重复点").css("color", "red") 24 } 25 } 26 }) 27 } 28 else { 29 alert(location.pathname); //拿到的是路径部分 30 location.href = "/login/?next=" + location.pathname 31 } 32 });