コード例 #1
0
ファイル: views.py プロジェクト: cnwalker/savesun
def predict_view(request):
    if request.method == "GET":
        end_time = timezone.now()
        start_time = end_time + relativedelta(hours=-1)
        predicitons = Prediction.objects.filter(date__range=(start_time,
                                                             end_time))
        if len(predicitons) == 0:
            new_prediction = Prediction(current_power=40000)
            new_prediction.save()
        all_predictions = Prediction.objects.all()
        return HttpResponse(
            json.dumps({
                'total':
                float(
                    reduce(lambda x, y: x.current_power + y.current_power,
                           all_predictions).current_power) /
                len(all_predictions)
            }))
コード例 #2
0
ファイル: forms.py プロジェクト: sebbacon/trevor
def _setup_initial_prediction(user, prediction, competition):
    this_year = datetime.datetime(settings.CURRENT_SEASON, 1, 1)
    if not Prediction.objects.filter(year=this_year,
                                     user=user,
                                     competition=competition)\
                             .count():        
        prediction_obj = Prediction(year=this_year,
                                    user=user,
                                    name=user.email,
                                    competition=competition)
        prediction_obj.save()

        for t_id in prediction:
            prediction_obj.teams.add(Team.objects.get(pk=t_id))
        prediction_obj.save()
        prediction_obj.calculateScore()
        prediction_obj.calculateGoalDiff()
        prediction_obj.calculatePosition()
        meta_competition = Competition.objects.get(
            pk=settings.CURRENT_META_COMPETITION_ID)
        runningscore = RunningScore.objects.create(
            name="Running score",
            user=user,
            competition=meta_competition)
コード例 #3
0
ファイル: views.py プロジェクト: caoilteguiry/sportsbrackets
def view_fixtures(request, tournament_id, user_id=None):
    # XXX: All of the following is very inefficient (hurriedly implemented to get things finished in
    # time for wc2010). I've begun work on a replacement view that uses joins instead of making 
    # queries within loops; will merge in once its finished.

    if user_id:
        user = User.objects.get(id=user_id)
    else:
        user = request.user


    now = datetime.datetime.now()  # TODO: Allow pardon of 1 minute maybe?
    if request.method == "POST":
        if user_id:
            raise PermissionDenied("Not allowed POST to this URL")
        # extract the pertinent POST values (i.e. those with numeric keys)
        predictions_req = dict([(k,v) for k,v in request.POST.items() if str(k).isdigit()])
        for fixture_id, result_type_id in predictions_req.items():
            try:
                fixture = Fixture.objects.get(pk=fixture_id)
            except ObjectDoesNotExist:
                # No such fixture
                continue
            
            if now > fixture.date:
                # Not allowed to update anymore
                continue
            
            try:
                result_type = ResultType.objects.get(pk=result_type_id)
            except ObjectDoesNotExist:
                # No such result type.
                continue

            
            # TODO: add a create_or_update() method for Prediction (i.e. PUT) 
            # (this kind of idiom must exist in django already surely?)
            try:
                # update if prediction exists already. TODO: Perhaps add a unique constraint on (user, prediction)
                prediction = Prediction.objects.filter(user=user).get(fixture=fixture)
                prediction.result = result_type
                prediction.save()
            except ObjectDoesNotExist:
                # prediction doesn't exist, lets add it
                prediction = Prediction(user=user, fixture=fixture, result=result_type)
                # FIXME: This is quite inefficient. Generate a comma-separated insert query instead. 
                prediction.save() 
        return redirect(request.get_full_path())
    
    
    all_result_types = ResultType.objects.all()  # TODO: error handling if no result types found?
    knockout_result_types = ResultType.objects.filter(Q(pk=1) | Q(pk=2))   # FIXME: hack (hard-coded values)

    # TODO: move this above the POST block?
    try:
        tournament = Tournament.objects.get(pk=tournament_id)
    except ObjectDoesNotExist:
        return HttpResponse('Tournament %s does not exist. <a href="/tournaments">View Tournaments</a>' % tournament_id)

    fixtures = Fixture.objects.filter(tournament=tournament_id).order_by("-date")
    # FIXME: This is pretty poor.. should really use a single SQL query to retrieve this data
    games = []  # this array stores dicts containing a fixture, prediction, is_disabled bool val, and 
    for fixture in fixtures:
        try:
            prediction = Prediction.objects.filter(fixture=fixture.id).get(user=user)
        except ObjectDoesNotExist:
            prediction = None
        
        is_disabled = False    
        if now > fixture.date or fixture.result:
            is_disabled = True
            
        if fixture.fixture_type.is_drawable:
            result_types = all_result_types
        else:
            result_types = knockout_result_types
        games.append({"fixture":fixture,
                      "prediction":prediction,
                      "is_disabled":is_disabled,
                      "result_types":result_types  # FIXME: inefficient
                      })
    
    c = csrf(request)
    c.update(locals())
    return render_to_response("fixtures.html", c, context_instance=RequestContext(request))