一天只能触发一次操作
需求:
学生可以给予导师评价,但是一天只能给予一次评价。
数据库:
class Appraise(models.Model): TYPE = ( (1, u'差'), (2, u'中'), (3, u'好'), ) student = models.ForeignKey('accounts.Student') teacher = models.ForeignKey('accounts.Teacher') appraise_type = models.SmallIntegerField(verbose_name="评价类型", blank=True, null=True, choices=TYPE) create_time = models.DateField(auto_now_add=True) status = models.SmallIntegerField(default=1) objects = AppraiseManager() class Meta: verbose_name = "学生评价导师记录" verbose_name_plural = "学生评价导师记录"
Html页面使用ajax传递数据
$(function(){ $("#good").click(function(){ if (!confirm("确定给予校内导师好评吗?")) return; $.ajax({ type: "POST", // 数据交换方式,如果递交的数据要修改后台数据库,则此处必须选择POST,反之为GET url: '{% url "student:appraise" %}', // 处理递交的数据的后台函数 data: {appraise: "3", teacherType:"1"}, // 递交的具体数据,使用key: value的方式传递 dataType: 'json', success: function (response) { // 处理完数据后前台的回调函数(即后台执行完之后前台接着要做的事) if (response['flag'] == true) { alert(response['msg']); } else { alert(response['msg']); } } }); }); })
后台接收
try: appraise = request.POST['appraise'] if request.POST['teacherType'] == "1": if Appraise.objects.filter(student=request.user.student, teacher=request.user.student.teacher): appraise = Appraise.objects.filter(student=request.user.student, teacher=request.user.student.teacher).order_by("-create_time")[0] now = datetime.datetime.now() last_time = appraise.create_time.strftime('%Y-%m-%d') d = now - datetime.datetime.strptime(last_time, '%Y-%m-%d') if d.days > 0: Appraise.objects.create(student=request.user.student, teacher=request.user.student.teacher, appraise_type=appraise) else: return json_response(False, '-1', "今日已评价过,请明日再评价!") else: Appraise.objects.create(student=request.user.student, teacher=request.user.student.teacher, appraise_type=appraise) except Appraise.DoesNotExist: return json_response(False, '-1', "评价失败") except Exception, e: print e return json_response(False, '-1', "评价失败") return json_response(True, '1', "评价成功")
首先要通过strftime将时间datetime.date转化为字符串格式,再通过strptime转化为datetime.datetime格式进行比较