def vote(request,image_id,value): cookie_key = "image_%s"%image_id days_expire = 1 if request.is_ajax and not request.COOKIES.get(cookie_key): try: user_ip = get_client_ip(request) time_ago = datetime.datetime.now()-datetime.timedelta(days=days_expire) Vote.objects.get(user_ip=user_ip,created__gt=time_ago,image_id=image_id) except ObjectDoesNotExist: response = HttpResponse() try: image = Image.objects.get(pk=image_id) except ObjectDoesNotExist: return response vote = Vote() vote.value = 1 if value=='up' else -1 vote.user_ip = user_ip vote.image = image vote.created = datetime.datetime.now() vote.save() image.rating = Vote.objects.filter(image=image)\ .aggregate(sum=Sum('value')).get('sum') image.save() recalc_sizes(image.miracle) image =Image.objects.get(id=image.pk) new_data = {'rating':image.rating,'id':image.pk,'size':image.size} new_data_encoded = json.dumps(new_data) response.write(new_data_encoded) set_cookie(response,cookie_key,True,days_expire) return response return HttpResponse()
def vote(request, tid): """ 用户给某个主题投票 """ tp = get_object_or_404(Topic, pk=tid) comment = request.POST.get('comment', ' ') try: Vote.objects.get(topic=tp, member=request.user) except Vote.DoesNotExist: vote = Vote(topic=tp, member=request.user, comment=comment) vote.save() return HttpResponseRedirect('/topic/%s/' % tid)