def vote(request, mlist_fqdn, message_id_hash): """ Add a rating to a given message identified by messageid. """ if request.method != 'POST': raise SuspiciousOperation if not request.user.is_authenticated(): return HttpResponse('You must be logged in to vote', content_type="text/plain", status=403) store = get_store(request) message = store.get_message_by_hash_from_list(mlist_fqdn, message_id_hash) if message is None: raise Http404 value = int(request.POST['vote']) if value not in [-1, 0, 1]: raise SuspiciousOperation # Checks if the user has already voted for a this message. try: v = Rating.objects.get(user=request.user, messageid=message_id_hash, list_address=mlist_fqdn) if v.vote == value: return HttpResponse("You've already cast this vote", content_type="text/plain", status=403) except Rating.DoesNotExist: if value != 0: v = Rating(list_address=mlist_fqdn, messageid=message_id_hash, vote=value) v.user = request.user else: return HttpResponse("There is no vote to cancel", content_type="text/plain", status=500) if value == 0: v.delete() else: v.vote = value v.save() # Extract all the votes for this message to refresh it set_message_votes(message, request.user) t = loader.get_template('messages/like_form.html') html = t.render( RequestContext(request, { "object": message, "message_id_hash": message_id_hash, })) result = { "like": message.likes, "dislike": message.dislikes, "html": html, } return HttpResponse(json.dumps(result), mimetype='application/javascript')
def test_vote_cancel(self): v = Rating(list_address="*****@*****.**", messageid="m1", vote=1) v.user = self.user v.save() v = Rating(list_address="*****@*****.**", messageid="m2", vote=-1) v.user = self.user v.save() for msg in ["m1", "m2"]: request = self.factory.post("/vote", {"vote": "0"}) request.user = self.user resp = vote(request, '*****@*****.**', msg) self.assertEqual(resp.status_code, 200) try: Rating.objects.get(user=self.user, messageid=msg, list_address='*****@*****.**') except Rating.DoesNotExist: pass else: self.fail("Vote for msg %s should have been deleted" % msg) result = json.loads(resp.content) self.assertEqual(result["like"], 0) self.assertEqual(result["dislike"], 0)