def up_down(request):
"""
网页最终页点赞
:param request:
:return:
"""
click_username = request.session.get('username')
if not click_username:
return redirect('/login/')
way = request.POST.get('way')
article_id = request.POST.get('article_id')
count_obj = models.Article.objects.filter(nid=article_id).first()
up_count = count_obj.up_count
down_count = count_obj.down_count
userinfo = models.UserInfo.objects.filter(username=click_username).first()
click_username_id = userinfo.nid
ret = {'status': None, 'msg': None, 'count': None}
count = None
try:
with transaction.atomic():
obj = models.UpDown.objects.filter(article_id=article_id, user_id=click_username_id).first()
if obj.up == 1:
if way == "up":
# 取消点赞
# 删除关系表
models.UpDown.objects.filter(article_id=article_id, user_id=click_username_id).delete()
# 统计点赞数
count = up_count - 1
count = 0 if count <= 0 else count
models.Article.objects.filter(nid=article_id).update(up_count=count)
ret['status'] = 1
ret['msg'] = '取消点赞'
else:
# 点踩
ret['status'] = 0
count = down_count
ret['msg'] = '你已点赞'
if obj.up == 0:
if way == "up":
# 点赞
ret['status'] = 1
count = up_count
ret['msg'] = '你已点踩'
else:
# 取消点踩
models.UpDown.objects.filter(article_id=article_id, user_id=click_username_id).delete()
count = down_count - 1
count = 0 if count <= 0 else count
models.Article.objects.filter(nid=article_id).update(down_count=count)
ret['status'] = 0
ret['msg'] = '取消点踩'
# 没有关系,既没有点赞也没有点踩
if way == "up":
models.UpDown.objects.create(article_id=article_id, user_id=click_username_id, up=1)
count = up_count + 1
models.Article.objects.filter(nid=article_id).update(up_count=count)
ret['status'] = 1
ret['msg'] = '点赞成功'
else:
models.UpDown.objects.create(article_id=article_id, user_id=click_username_id, up=0)
count = down_count + 1
models.Article.objects.filter(nid=article_id).update(down_count=count)
ret['status'] = 0
ret['msg'] = '点踩成功'
except:
pass
ret['count'] = count
return HttpResponse(json.dumps(ret))