###投票应用,给老师投票,且每个用户只有三票

1.将字典转换成json格式
2.ajax请求

####views.py文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def make_good_comment(request, no):
teacher = Teacher.objects.get(pk=no)
teacher.good_count += 1
teacher.save()

# 次一点的方法:发一个重定向参数,回到首页,写的是url的名字
# return redirect('index')
# 使用ajax分布式加载
# 构造一个字典,context
ctx = {'code': 200, 'good': teacher.good_count}
'''
将返回的字典转换成json格式:
# 将字典转成json格式的函数,一个字符串,返回文本,指定返回的是json格式
# 这是MIME类型,Multipurpose Internet Mail Extension 告诉浏览器给的是什么类型的数据
# image/jpeg, image/png, image/gif, application/msword, application/pdf, audio/mp3, video/mpeg
# 因特网是tcp/ip协议构建的网络
# 如果返回的json数据中有中文,还要加上charset=utf-8
'''
return HttpResponse(json.dumps(ctx), content_type='application/json')


def make_bad_comment(request, no):
teacher = Teacher.objects.get(pk=no)
teacher.bad_count += 1
teacher.save()
ctx = {'code': 200, 'bad': teacher.bad_count}
return HttpResponse(json.dumps(ctx), content_type='application/json')

urls文件

1
2
path('good/<int:no>/', views.make_comment),
path('bad/<int:no>/', views.make_comment),

teachers.html文件:使用ajax方法投票

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<script>
$(function(){
{#绑定点击事件#}
$('.basic .button').on('click', function(evt){
{#阻止a标签的默认行为#}
evt.preventDefault();
{#取到的原生js对象#}
var $a = $(evt.target);
{#attr方法可以取属性也可以改属性,jquery的方法#}
var url = $a.attr('href');
{#传入一个json对象,#}
$.ajax({
'url':url,
'type':'get',
'data':{},
'dataType':'json',
'success': function(json){
if(json.code == 200){
$a.text(json.result);
console.log('请求成功')
}else if(json.code == 403){
alert('票数不足')
}
},
'error': function(json){
console.log('请求错误')
}
});
});
});

优化:将两个投票的方法合二为一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def make_comment(request, no):
ctx = {'code': 200}
if 'user' in request.session and request.session['user']:
user = request.session['user']
if user.tcounter > 0:
try:
# 去request里面拿path属性,就是你请求的url,拿到like or dislike
# /good/3,拿到主机或者域名是host,get_full_path
# s是我的资源,?后面是请求参数,服务器传递的查询字符串
teacher = Teacher.objects.get(pk=no)
# request.method是拿到请求的类型
if request.path.startswith('/good'):
teacher.good_count += 1
ctx['result'] = f'like({teacher.gcount})'
else:
teacher.bad_count += 1
ctx['result'] = f'dislike({teacher.bcount})'
teacher.save()
user.tcounter -= 1
# 改变tcounter
User.objects.filter(username__exact=user.username).\
update(tcounter=user.tcounter)
request.session['user'] = user
# user.save()
# except Teacher.DoesNotExist:
# ctx['code'] = 404
except:
return render(request, 'error.html', {})
else:
ctx['code'] = 403
ctx['result'] = '票数不足'
else:
ctx['code'] = 302
ctx['result'] = '请先登录'
return HttpResponse(json.dumps(ctx), content_type='application/json', charset='utf-8')