picture-tournament/pt/views.py

84 lines
2.6 KiB
Python

import logging
import random
from django.core.urlresolvers import reverse
from django.db.models import Max
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from . import models
log = logging.getLogger('picture_tournament')
# Create your views here.
def compare(request):
if "left" not in request.session:
left_pic = random_pic()
request.session["left"] = left_pic.id
if "right" not in request.session:
right_pic = random_pic()
request.session["right"] = right_pic.id
left_pic = models.Picture.objects.get(id=request.session["left"])
right_pic = models.Picture.objects.get(id=request.session["right"])
context = {
"left": left_pic,
"right": right_pic,
}
return HttpResponse(render(request, 'pt/compare.html', context))
def random_pic():
max_id = models.Picture.objects.all().aggregate(Max('id'))["id__max"]
log.debug("max_id = %s", max_id)
while True:
id = random.randint(1, max_id)
pics = models.Picture.objects.filter(id=id)
if len(pics) == 1:
return pics[0]
def left_wins(request):
left = models.Picture.objects.get(id=request.session["left"])
right = models.Picture.objects.get(id=request.session["right"])
expected = 1 / (1 + 10**((right.elo - left.elo) / 400))
log.info("before: left=%f, right=%f, expected=%f", left.elo, right.elo, expected)
adjust = (1 - expected) * 20
left.elo += adjust
left.save()
right.elo -= adjust
right.save()
log.info("after: left=%f, right=%f", left.elo, right.elo)
del request.session["right"]
return HttpResponseRedirect(reverse('compare'))
def right_wins(request):
left = models.Picture.objects.get(id=request.session["left"])
right = models.Picture.objects.get(id=request.session["right"])
expected = 1 / (1 + 10**((left.elo - right.elo) / 400))
log.info("before: left=%f, right=%f, expected=%f", left.elo, right.elo, expected)
adjust = (1 - expected) * 20
left.elo -= adjust
left.save()
right.elo += adjust
right.save()
log.info("after: left=%f, right=%f", left.elo, right.elo)
del request.session["left"]
return HttpResponseRedirect(reverse('compare'))
def refresh(request):
del request.session["left"]
del request.session["right"]
return HttpResponseRedirect(reverse('compare'))
def top(request):
top = models.Picture.objects.all().order_by("-elo")[0:9]
context = { "top": top }
return HttpResponse(render(request, 'pt/top.html', context))