Esempio n. 1
0
def view_room(request, room_id):
    room_id = int(room_id)
    try:
        room = Room.objects.get(pk=room_id)
    except Room.DoesNotExist:
        return redirect_and_flash_error(request, "Room not found")
    if request.method == "POST":
        form = RoomForm(request.POST, instance=room)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request,
                    "Room name cannot be validated, most likely a non-existent room"
                )
            return redirect_and_flash_success(
                request, "School {} updated successfully".format(
                    form.cleaned_data["name"]))
    else:
        form = RoomForm(instance=room)
    return render(request, "common/data_entry.html", {
        "form": form,
        "links": [],
        "title": "Viewing Room: %s" % (room.name)
    })
Esempio n. 2
0
def view_debater(request, debater_id):
    debater_id = int(debater_id)
    try:
        debater = Debater.objects.get(pk=debater_id)
    except Debater.DoesNotExist:
        return redirect_and_flash_error(request, "No such debater")
    if request.method == 'POST':
        form = DebaterForm(request.POST,instance=debater)
        if form.is_valid():
            try:
               form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                        "Debater name cannot be validated, most likely a non-existent debater")
            return redirect_and_flash_success(request,
                    "Debater {} updated successfully".format(form.cleaned_data['name']))
    else:
        rounds = RoundStats.objects.filter(debater=debater)
        rounds = sorted(list(rounds), key=lambda x: x.round.round_number)
        form = DebaterForm(instance=debater)
        # Really only should be one
        teams = Team.objects.filter(debaters = debater)
        links = []
        for team in teams:
            links.append(('/team/'+str(team.id)+'/', "View %s"%team.name))

        return render(request, 'common/data_entry.html', 
                                 {'form': form,
                                  'debater_obj': debater,
                                  'links': links,
                                  'debater_rounds': rounds,
                                  'title':"Viewing Debater: %s"%(debater.name)})
Esempio n. 3
0
def view_school(request, school_id):
    school_id = int(school_id)
    try:
        school = School.objects.get(pk=school_id)
    except School.DoesNotExist:
        return redirect_and_flash_error(request, "School not found")
    if request.method == "POST":
        form = SchoolForm(request.POST, instance=school)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request,
                    "School name cannot be validated, most likely a non-existent school"
                )
            return redirect_and_flash_success(
                request, "School {} updated successfully".format(
                    form.cleaned_data["name"]))
    else:
        form = SchoolForm(instance=school)
        links = [("/school/" + str(school_id) + "/delete/", "Delete")]
        return render(
            request, "common/data_entry.html", {
                "form": form,
                "links": links,
                "title": "Viewing School: %s" % (school.name)
            })
Esempio n. 4
0
def view_judge(request, judge_id):
    judge_id = int(judge_id)
    try:
        judge = Judge.objects.get(pk=judge_id)
    except Judge.DoesNotExist:
        return redirect_and_flash_error(request, "Judge not found")
    if request.method == "POST":
        form = JudgeForm(request.POST, instance=judge)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request, "Judge information cannot be validated")
            return redirect_and_flash_success(
                request, "Judge {} updated successfully".format(
                    form.cleaned_data["name"]))
    else:
        form = JudgeForm(instance=judge)
    base_url = "/judge/" + str(judge_id) + "/"
    scratch_url = base_url + "scratches/view/"
    links = [(scratch_url, "Scratches for {}".format(judge.name))]
    return render(
        request, "common/data_entry.html", {
            "form": form,
            "links": links,
            "title": "Viewing Judge: {}".format(judge.name)
        })
Esempio n. 5
0
def view_judge(request, judge_id):
    judge_id = int(judge_id)
    try:
        judge = Judge.objects.get(pk=judge_id)
    except Judge.DoesNotExist:
        return redirect_and_flash_error(request, "Judge not found")
    if request.method == 'POST':
        form = JudgeForm(request.POST,instance=judge)
        if form.is_valid():
            try:
               form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                        "Judge information cannot be validated")
            return redirect_and_flash_success(request,
                    "Judge {} updated successfully".format(form.cleaned_data['name']))
    else:
        form = JudgeForm(instance=judge)
    base_url = '/judge/'+str(judge_id)+'/'
    scratch_url = base_url + 'scratches/view/'
    delete_url =  base_url + 'delete/'
    links = [(scratch_url, 'Scratches for {}'.format(judge.name))]
    return render(request, 'common/data_entry.html', 
                                {'form': form,
                                'links': links,
                                'title': 'Viewing Judge: {}'.format(judge.name)})
Esempio n. 6
0
def add_scratches(request, judge_id, number_scratches):
    try:
        judge_id,number_scratches = int(judge_id),int(number_scratches)
    except ValueError:
        return redirect_and_flash_error(request, "Got invalid data")
    try:
        judge = Judge.objects.get(pk=judge_id)
    except Judge.DoesNotExist:
        return redirect_and_flash_error(request, "No such judge")

    if request.method == 'POST':
        forms = [ScratchForm(request.POST, prefix=str(i)) for i in range(1,number_scratches+1)]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return redirect_and_flash_success(request,
                    "Scratches created successfully")
    else:
        forms = [ScratchForm(prefix=str(i), initial={'judge':judge_id,'scratch_type':0}) for i in range(1,number_scratches+1)]
    return render(request, 'common/data_entry_multiple.html', 
                             {'forms': list(zip(forms,[None]*len(forms))),
                              'data_type':'Scratch',
                              'title':"Adding Scratch(es) for %s"%(judge.name)})
Esempio n. 7
0
def pretty_tab_card(request, team_id):
    try:
        team_id = int(team_id)
    except Exception:
        return redirect_and_flash_error(request, "Invalid team id")
    team = Team.objects.get(pk=team_id)
    return render(request, "tab/pretty_tab_card.html", {"team": team})
def enter_result(request, round_id, form_class=OutroundResultEntryForm):

    round_obj = Outround.objects.get(id=round_id)

    redirect_to = reverse("outround_pairing_view",
                          kwargs={
                              "num_teams": round_obj.num_teams,
                              "type_of_round": round_obj.type_of_round
                          })

    if request.method == "POST":
        form = form_class(request.POST, round_instance=round_obj)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request, "Invalid round result, could not remedy.")
            return redirect_and_flash_success(request,
                                              "Result entered successfully",
                                              path=redirect_to)
    else:
        form_kwargs = {"round_instance": round_obj}
        form = form_class(**form_kwargs)

    return render(
        request, "outrounds/ballot.html", {
            "form": form,
            "title": "Entering Ballot for {}".format(round_obj),
            "gov_team": round_obj.gov_team,
            "opp_team": round_obj.opp_team,
        })
Esempio n. 9
0
def enter_team(request):
    if request.method == "POST":
        form = TeamEntryForm(request.POST)
        if form.is_valid():
            try:
                team = form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request,
                    "Team name cannot be validated, most likely a duplicate school"
                )
            num_forms = form.cleaned_data["number_scratches"]
            if num_forms > 0:
                return HttpResponseRedirect("/team/" + str(team.pk) +
                                            "/scratches/add/" + str(num_forms))
            else:
                return redirect_and_flash_success(
                    request,
                    "Team {} created successfully".format(
                        team.display_backend),
                    path="/")
    else:
        form = TeamEntryForm()
    return render(request, "common/data_entry.html", {
        "form": form,
        "title": "Create Team"
    })
Esempio n. 10
0
def assign_judges_to_pairing(request):
    current_round_number = TabSettings.objects.get(key="cur_round").value - 1
    if request.method == "POST":
        panel_points, errors = [], []
        potential_panel_points = [
            k for k in list(request.POST.keys()) if k.startswith("panel_")
        ]
        for point in potential_panel_points:
            try:
                point = int(point.split("_")[1])
                num = float(request.POST["panel_{0}".format(point)])
                if num > 0.0:
                    panel_points.append((Round.objects.get(id=point), num))
            except Exception as e:
                emit_current_exception()
                errors.append(e)

        panel_points.reverse()
        rounds = list(Round.objects.filter(round_number=current_round_number))
        judges = [
            ci.judge
            for ci in CheckIn.objects.filter(round_number=current_round_number)
        ]
        try:
            backup.backup_round("round_%s_before_judge_assignment" %
                                current_round_number)
            assign_judges.add_judges(rounds, judges, panel_points)
        except Exception as e:
            emit_current_exception()
            return redirect_and_flash_error(
                request, "Got error during judge assignment")
    return redirect("/pairings/status/")
Esempio n. 11
0
def assign_judges_to_pairing(request):
    current_round_number = TabSettings.objects.get(key="cur_round").value - 1
    if request.method == 'POST':
        panel_points, errors = [], []
        potential_panel_points = [k for k in list(request.POST.keys()) if k.startswith('panel_')]
        for point in potential_panel_points:
           try:
               point = int(point.split("_")[1])
               num = float(request.POST["panel_{0}".format(point)])
               if num > 0.0:
                   panel_points.append((Round.objects.get(id=point), num))
           except Exception as e:
               emit_current_exception()
               errors.append(e)
               pass

        panel_points.reverse()
        rounds = list(Round.objects.filter(round_number=current_round_number))
        judges = [ci.judge for ci in CheckIn.objects.filter(round_number=current_round_number)]
        try:
            backup.backup_round("round_%s_before_judge_assignment" % current_round_number)
            assign_judges.add_judges(rounds, judges, panel_points)
        except Exception as e:
            emit_current_exception()
            return redirect_and_flash_error(request,
                    "Got error during judge assignment")
    return redirect('/pairings/status/')
Esempio n. 12
0
def enter_result(request, round_id, form_class=ResultEntryForm, ballot_code=None, redirect_to="/pairings/status"):
    round_obj = Round.objects.get(id=round_id)

    if request.method == "POST":
        form = form_class(request.POST, round_instance=round_obj)
        if form.is_valid():
            try:
                result = form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                        "Invalid round result, could not remedy.")
            return redirect_and_flash_success(request,
                    "Result entered successfully",
                    path=redirect_to)
    else:
        form_kwargs = { "round_instance": round_obj }
        if ballot_code:
            form_kwargs["ballot_code"] = ballot_code
        form = form_class(**form_kwargs)

    return render(request, "ballots/round_entry.html",
                              {"form": form,
                               "title": 'Entering Ballot for {}'.format(round_obj),
                               "gov_team": round_obj.gov_team,
                               "opp_team": round_obj.opp_team,
                               "ballot_code": ballot_code})
Esempio n. 13
0
def enter_result(request,
                 round_id,
                 form_class=ResultEntryForm,
                 ballot_code=None,
                 redirect_to="/pairings/status"):
    round_obj = Round.objects.get(id=round_id)

    if request.method == "POST":
        form = form_class(request.POST, round_instance=round_obj)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request, "Invalid round result, could not remedy.")
            return redirect_and_flash_success(request,
                                              "Result entered successfully",
                                              path=redirect_to)
    else:
        form_kwargs = {"round_instance": round_obj}
        if ballot_code:
            form_kwargs["ballot_code"] = ballot_code
        form = form_class(**form_kwargs)

    return render(
        request, "ballots/round_entry.html", {
            "form": form,
            "title": "Entering Ballot for {}".format(round_obj),
            "gov_team": round_obj.gov_team,
            "opp_team": round_obj.opp_team,
            "ballot_code": ballot_code
        })
Esempio n. 14
0
def view_scratches(request, judge_id):
    try:
        judge_id = int(judge_id)
    except ValueError:
        return redirect_and_flash_error(request, "Received invalid data")
    scratches = Scratch.objects.filter(judge=judge_id)
    judge = Judge.objects.get(pk=judge_id)
    number_scratches = len(scratches)
    if request.method == 'POST':
        forms = [ScratchForm(request.POST, prefix=str(i),instance=scratches[i-1]) for i in range(1,number_scratches+1)]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return redirect_and_flash_success(request,
                    "Scratches created successfully")
    else:
        forms = [ScratchForm(prefix=str(i), instance=scratches[i-1]) for i in range(1,len(scratches)+1)]
    delete_links = ["/judge/"+str(judge_id)+"/scratches/delete/"+str(scratches[i].id) for i in range(len(scratches))]
    links = [('/judge/'+str(judge_id)+'/scratches/add/1/','Add Scratch')]

    return render(request, 'common/data_entry_multiple.html',
                             {'forms': list(zip(forms,delete_links)),
                              'data_type':'Scratch',
                              'links':links,
                              'title':"Viewing Scratch Information for %s"%(judge.name)})
Esempio n. 15
0
def pretty_tab_card(request, team_id):
    try:
        team_id = int(team_id)
    except:
        return redirect_and_flash_error(request, "Invalid team id")
    team = Team.objects.get(pk=team_id)
    return render(request, 'tab/pretty_tab_card.html', {'team':team})
Esempio n. 16
0
def view_team(request, team_id):
    team_id = int(team_id)
    try:
        team = Team.objects.get(pk=team_id)
        stats = []
        stats.append(("Wins", tab_logic.tot_wins(team)))
        stats.append(("Total Speaks", tab_logic.tot_speaks(team)))
        stats.append(("Govs", tab_logic.num_govs(team)))
        stats.append(("Opps", tab_logic.num_opps(team)))
        stats.append(("Avg. Opp Wins", tab_logic.opp_strength(team)))
        stats.append(("Been Pullup", tab_logic.pull_up_count(team)))
        stats.append(("Hit Pullup", tab_logic.hit_pull_up(team)))
    except Team.DoesNotExist:
        return redirect_and_flash_error(request, "Team not found")
    if request.method == "POST":
        form = TeamForm(request.POST, instance=team)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request,
                    "An error occured, most likely a non-existent team")
            return redirect_and_flash_success(
                request, "Team {} updated successfully".format(
                    form.cleaned_data["name"]))
    else:
        form = TeamForm(instance=team)
        links = [("/team/" + str(team_id) + "/scratches/view/",
                  "Scratches for {}".format(team.display_backend))]
        for deb in team.debaters.all():
            links.append(
                ("/debater/" + str(deb.id) + "/", "View %s" % deb.name))
        return render(
            request, "common/data_entry.html", {
                "title": "Viewing Team: %s" % (team.display_backend),
                "form": form,
                "links": links,
                "team_obj": team,
                "team_stats": stats
            })

    return render(request, "common/data_entry.html", {"form": form})
Esempio n. 17
0
def manual_backup(request):
    try:
        cur_round, btime = TabSettings.objects.get(key="cur_round").value, int(time.time())
        now = datetime.datetime.fromtimestamp(btime).strftime("%Y-%m-%d_%I:%M")
        backup.backup_round("manual_backup_round_{}_{}_{}".format(cur_round, btime, now))
    except:
        emit_current_exception()
        return redirect_and_flash_error(request, "Error creating backup")
    return redirect_and_flash_success(request,
            "Backup created for round {} at timestamp {}".format(cur_round, btime))
Esempio n. 18
0
def delete_scratch(request, item_id, scratch_id):
    try:
        scratch_id = int(scratch_id)
        scratch = Scratch.objects.get(pk=scratch_id)
        scratch.delete()
    except Scratch.DoesNotExist:
        return redirect_and_flash_error(request,
                "This scratch does not exist, please try again with a valid id.")
    return redirect_and_flash_success(request,
            "Scratch deleted successfully",
            path="/")
Esempio n. 19
0
def break_teams(request):
    if request.method == "POST":
        # Perform the break
        backup.backup_round("before_the_break_%s" %
                            (timezone.now().strftime("%H:%M"), ))

        success, msg = outround_tab_logic.perform_the_break()

        if success:
            return redirect_and_flash_success(request,
                                              msg,
                                              path="/outround_pairing")
        return redirect_and_flash_error(request, msg, path="/")

    # See if we can pair the round
    title = "Pairing Outrounds"
    current_round_number = 0

    previous_round_number = TabSettings.get("tot_rounds", 5)

    check_status = []

    msg = "All Rounds properly entered for Round %s" % (previous_round_number)

    ready_to_pair = "Yes"
    ready_to_pair_alt = "Checks passed!"
    try:
        tab_logic.have_properly_entered_data(current_round_number)
        check_status.append((msg, "Yes", "All rounds look good"))
    except PrevRoundNotEnteredError as e:
        ready_to_pair = "No"
        ready_to_pair_alt = str(e)
        check_status.append(
            (msg, "No", "Not all rounds are entered. %s" % str(e)))
    except ByeAssignmentError as e:
        ready_to_pair = "No"
        ready_to_pair_alt = str(e)
        check_status.append(
            (msg, "No", "You have a bye and results. %s" % str(e)))
    except NoShowAssignmentError as e:
        ready_to_pair = "No"
        ready_to_pair_alt = str(e)
        check_status.append(
            (msg, "No", "You have a noshow and results. %s" % str(e)))

    rooms = outround_tab_logic.have_enough_rooms_before_break()
    msg = "N/2 Rooms available Round Out-rounds? Need {0}, have {1}".format(
        rooms[1][1], rooms[1][0])
    if rooms[0]:
        check_status.append((msg, "Yes", "Rooms are checked in"))
    else:
        check_status.append((msg, "No", "Not enough rooms"))

    return render(request, "pairing/pair_round.html", locals())
Esempio n. 20
0
def start_new_tourny(request):
    try:
        clear_db()
        TabSettings.set("cur_round", 1)
        TabSettings.set("tot_rounds", 5)
        TabSettings.set("lenient_late", 0)
    except Exception:
        emit_current_exception()
        return redirect_and_flash_error(
            request, "Invalid tournament state, try resetting from a back-up")
    return redirect_and_flash_success(request, "New tournament started")
Esempio n. 21
0
def delete_scratch(request, item_id, scratch_id):
    try:
        scratch_id = int(scratch_id)
        scratch = Scratch.objects.get(pk=scratch_id)
        scratch.delete()
    except Scratch.DoesNotExist:
        return redirect_and_flash_error(
            request,
            "This scratch does not exist, please try again with a valid id.")
    return redirect_and_flash_success(request,
                                      "Scratch deleted successfully",
                                      path="/")
Esempio n. 22
0
def view_room(request, room_id):
    room_id = int(room_id)
    try:
        room = Room.objects.get(pk=room_id)
    except Room.DoesNotExist:
        return redirect_and_flash_error(request, "Room not found")
    if request.method == 'POST':
        form = RoomForm(request.POST,instance=room)
        if form.is_valid():
            try:
               form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                        "Room name cannot be validated, most likely a non-existent room")
            return redirect_and_flash_success(request,
                    "School {} updated successfully".format(form.cleaned_data['name']))
    else:
        form = RoomForm(instance=room)
    return render(request, 'common/data_entry.html',
                                {'form': form, 'links': [],
                                'title': "Viewing Room: %s"%(room.name)})
Esempio n. 23
0
def start_new_tourny(request):
    try:
        clear_db()
        #TODO: Unify this with initialize_tourney
        TabSettings.set("cur_round", 1)
        TabSettings.set("tot_rounds", 5)
        TabSettings.set("lenient_late", 0)
    except Exception as e:
        emit_current_exception()
        return redirect_and_flash_error(request,
                "Invalid tournament state, try resetting from a back-up")
    return redirect_and_flash_success(request, "New tournament started")
Esempio n. 24
0
def manual_backup(request):
    try:
        cur_round, btime = TabSettings.objects.get(key="cur_round").value, int(
            time.time())
        now = datetime.datetime.fromtimestamp(btime).strftime("%Y-%m-%d_%I:%M")
        backup.backup_round("manual_backup_round_{}_{}_{}".format(
            cur_round, btime, now))
    except Exception:
        emit_current_exception()
        return redirect_and_flash_error(request, "Error creating backup")
    return redirect_and_flash_success(
        request,
        "Backup created for round {} at timestamp {}".format(cur_round, btime))
Esempio n. 25
0
def view_debater(request, debater_id):
    debater_id = int(debater_id)
    try:
        debater = Debater.objects.get(pk=debater_id)
    except Debater.DoesNotExist:
        return redirect_and_flash_error(request, "No such debater")
    if request.method == "POST":
        form = DebaterForm(request.POST, instance=debater)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request,
                    "Debater name can't be validated. Probably a non-existent debater"
                )
            return redirect_and_flash_success(
                request, "Debater {} updated successfully".format(
                    form.cleaned_data["name"]))
    else:
        rounds = RoundStats.objects.filter(debater=debater)
        rounds = sorted(list(rounds), key=lambda x: x.round.round_number)
        form = DebaterForm(instance=debater)
        # Really only should be one
        teams = Team.objects.filter(debaters=debater)
        links = []
        for team in teams:
            links.append(
                ("/team/" + str(team.id) + "/", "View %s" % team.name))

        return render(
            request, "common/data_entry.html", {
                "form": form,
                "debater_obj": debater,
                "links": links,
                "debater_rounds": rounds,
                "title": "Viewing Debater: %s" % (debater.name)
            })
Esempio n. 26
0
def view_school(request, school_id):
    school_id = int(school_id)
    try:
        school = School.objects.get(pk=school_id)
    except School.DoesNotExist:
        return redirect_and_flash_error(request, "School not found")
    if request.method == 'POST':
        form = SchoolForm(request.POST,instance=school)
        if form.is_valid():
            try:
               form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                        "School name cannot be validated, most likely a non-existent school")
            return redirect_and_flash_success(request,
                    "School {} updated successfully".format(form.cleaned_data['name']))
    else:
        form = SchoolForm(instance=school)
        links = [('/school/'+str(school_id)+'/delete/', 'Delete')]
        return render(request, 'common/data_entry.html',
                                 {'form': form,
                                  'links': links,
                                  'title': "Viewing School: %s" %(school.name)})
Esempio n. 27
0
def public_view_teams(request):
    display_teams = TabSettings.get("teams_public", 0)

    if not request.user.is_authenticated and not display_teams:
        return redirect_and_flash_error(request,
                                        "This view is not public",
                                        path="/")

    return render(
        request, "public/teams.html", {
            "teams": Team.objects.order_by("-checked_in",
                                           "school__name").all(),
            "num_checked_in": Team.objects.filter(checked_in=True).count()
        })
Esempio n. 28
0
def add_scratches(request, team_id, number_scratches):
    try:
        team_id, number_scratches = int(team_id), int(number_scratches)
    except ValueError:
        return redirect_and_flash_error(request, "Received invalid data")
    try:
        team = Team.objects.get(pk=team_id)
    except Team.DoesNotExist:
        return redirect_and_flash_error(request,
                                        "The selected team does not exist")
    if request.method == "POST":
        forms = [
            ScratchForm(request.POST, prefix=str(i))
            for i in range(1, number_scratches + 1)
        ]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return redirect_and_flash_success(
                request, "Scratches created successfully")
    else:
        forms = [
            ScratchForm(prefix=str(i),
                        initial={
                            "team": team_id,
                            "scratch_type": 0
                        }) for i in range(1, number_scratches + 1)
        ]
    return render(
        request, "common/data_entry_multiple.html", {
            "forms": list(zip(forms, [None] * len(forms))),
            "data_type": "Scratch",
            "title": "Adding Scratch(es) for %s" % (team.display_backend)
        })
Esempio n. 29
0
def add_scratches(request, judge_id, number_scratches):
    try:
        judge_id, number_scratches = int(judge_id), int(number_scratches)
    except ValueError:
        return redirect_and_flash_error(request, "Got invalid data")
    try:
        judge = Judge.objects.get(pk=judge_id)
    except Judge.DoesNotExist:
        return redirect_and_flash_error(request, "No such judge")

    if request.method == "POST":
        forms = [
            ScratchForm(request.POST, prefix=str(i))
            for i in range(1, number_scratches + 1)
        ]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return redirect_and_flash_success(
                request, "Scratches created successfully")
    else:
        forms = [
            ScratchForm(prefix=str(i),
                        initial={
                            "judge": judge_id,
                            "scratch_type": 0
                        }) for i in range(1, number_scratches + 1)
        ]
    return render(
        request, "common/data_entry_multiple.html", {
            "forms": list(zip(forms, [None] * len(forms))),
            "data_type": "Scratch",
            "title": "Adding Scratch(es) for %s" % (judge.name)
        })
Esempio n. 30
0
def view_team(request, team_id):
    team_id = int(team_id)
    try:
        team = Team.objects.get(pk=team_id)
        stats = []
        stats.append(("Wins", tab_logic.tot_wins(team)))
        stats.append(("Total Speaks", tab_logic.tot_speaks(team)))
        stats.append(("Govs", tab_logic.num_govs(team)))
        stats.append(("Opps", tab_logic.num_opps(team)))
        stats.append(("Avg. Opp Wins", tab_logic.opp_strength(team)))
        stats.append(("Been Pullup", tab_logic.pull_up_count(team)))
        stats.append(("Hit Pullup", tab_logic.hit_pull_up_count(team)))
    except Team.DoesNotExist:
        return redirect_and_flash_error(request, "Team not found")
    if request.method == 'POST':
        form = TeamForm(request.POST,instance=team)
        if form.is_valid():
            try:
               form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                        "An error occured, most likely a non-existent team")
            return redirect_and_flash_success(request,
                    "Team {} updated successfully".format(form.cleaned_data["name"]))
    else:
        form = TeamForm(instance=team)
        links = [('/team/'+str(team_id)+'/scratches/view/','Scratches for {}'.format(team.name))]
        for deb in team.debaters.all():
            links.append(('/debater/'+str(deb.id)+'/', "View %s" % deb.name))
        return render(request, 'common/data_entry.html', 
                                 {'title':"Viewing Team: %s"%(team.name),
                                  'form': form,
                                  'links': links,
                                  'team_obj':team,
                                  'team_stats':stats})

    return render(request, 'common/data_entry.html', {'form': form})
Esempio n. 31
0
def enter_e_ballot(request, ballot_code):
    if request.method == "POST":
        round_id = request.POST.get("round_instance")

        if round_id:
            return enter_result(request,
                                round_id,
                                EBallotForm,
                                ballot_code,
                                redirect_to="/")
        else:
            message = """
                      Missing necessary form data. Please go to tab if this
                      error persists
                      """

    current_round = TabSettings.get(key="cur_round") - 1
    rounds = Round.objects.filter(judges__ballot_code=ballot_code.lower())
    rounds = rounds.filter(round_number=current_round)
    judge = Judge.objects.filter(ballot_code=ballot_code).first()

    if not judge:
        message = """
                    No judges with the ballot code "%s." Try submitting again, or
                    go to tab to resolve the issue.
                    """ % ballot_code
    elif TabSettings.get("pairing_released", 0) != 1:
        message = "Pairings for this round have not been released."
    elif rounds.count() > 1:
        message = """
                Found more than one ballot for you this round.
                Go to tab to resolve this error.
                """
    elif rounds.count() == 0:
        message = """
                Could not find a ballot for you this round. Go to tab
                to resolve the issue if you believe you were paired in.
                """
    elif rounds.first().chair != judge:
        message = """
                You are not the chair of this round. If you are on a panel,
                only the chair can submit an e-ballot. If you are not on a
                panel, go to tab and make sure the chair is properly set for
                the round.
                """
    else:
        return enter_result(request,
                            rounds.first().id, EBallotForm, ballot_code)
    return redirect_and_flash_error(request, message, path="/accounts/login")
Esempio n. 32
0
def delete_school(request, school_id):
    error_msg = None
    try :
        school_id = int(school_id)
        school = School.objects.get(pk=school_id)
        school.delete()
    except School.DoesNotExist:
        error_msg = "That school does not exist"
    except Exception as e:
        error_msg = str(e)
    if error_msg:
        return redirect_and_flash_error(request, error_msg)
    return redirect_and_flash_success(request,
            "School deleted successfully",
            path="/")
Esempio n. 33
0
def public_view_judges(request):
    display_judges = TabSettings.get("judges_public", 0)

    if not request.user.is_authenticated and not display_judges:
        return redirect_and_flash_error(request,
                                        "This view is not public",
                                        path="/")

    num_rounds = TabSettings.get("tot_rounds", 5)
    rounds = [num for num in range(1, num_rounds + 1)]

    return render(request, "public/judges.html", {
        "judges": Judge.objects.order_by("name").all(),
        "rounds": rounds
    })
Esempio n. 34
0
def delete_school(request, school_id):
    error_msg = None
    try:
        school_id = int(school_id)
        school = School.objects.get(pk=school_id)
        school.delete()
    except School.DoesNotExist:
        error_msg = "That school does not exist"
    except Exception as e:
        error_msg = str(e)
    if error_msg:
        return redirect_and_flash_error(request, error_msg)
    return redirect_and_flash_success(request,
                                      "School deleted successfully",
                                      path="/")
Esempio n. 35
0
def enter_debater(request):
    if request.method == 'POST':
        form = DebaterForm(request.POST)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                        "Debater name cannot be validated, most likely a duplicate debater")
            return redirect_and_flash_success(request,
                    "Debater {} created successfully".format(form.cleaned_data['name']),
                    path="/")
    else:
        form = DebaterForm()
    return render(request, 'common/data_entry.html',
                             {'form': form, 'title': "Create Debater:"})
Esempio n. 36
0
def enter_judge(request):
    if request.method == 'POST':
        form = JudgeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                cd = form.cleaned_data
                return redirect_and_flash_error(request,
                        "Judge cannot be validated")
            return redirect_and_flash_success(request,
                    "Judge {} created successfully".format(form.cleaned_data['name']),
                    path="/")
    else:
        form = JudgeForm(first_entry=True)
    return render(request, 'common/data_entry.html',
                              {'form': form, 'title': "Create Judge"})
Esempio n. 37
0
def enter_e_ballot(request, ballot_code):
    if request.method == "POST":
        round_id = request.POST.get("round_instance")

        if round_id:
            return enter_result(request, round_id, EBallotForm, ballot_code,
                    redirect_to="/")
        else:
            message = """
                      Missing necessary form data. Please go to tab if this
                      error persists
                      """

    current_round = TabSettings.get(key="cur_round") - 1
    rounds = Round.objects.filter(judges__ballot_code=ballot_code.lower())
    rounds = rounds.filter(round_number=current_round)
    judge = Judge.objects.filter(ballot_code=ballot_code).first()

    if not judge:
        message = """
                    No judges with the ballot code "%s." Try submitting again, or
                    go to tab to resolve the issue.
                    """ % ballot_code
    elif TabSettings.get("pairing_released", 0) != 1:
        message = "Pairings for this round have not been released."
    elif rounds.count() > 1:
        message = """
                Found more than one ballot for you this round.
                Go to tab to resolve this error.
                """
    elif rounds.count() == 0:
        message = """
                Could not find a ballot for you this round. Go to tab
                to resolve the issue if you believe you were paired in.
                """
    elif rounds.first().chair != judge:
        message = """
                You are not the chair of this round. If you are on a panel,
                only the chair can submit an e-ballot. If you are not on a
                panel, go to tab and make sure the chair is properly set for
                the round.
                """
    else:
        return enter_result(request, rounds.first().id, EBallotForm, ballot_code)
    return redirect_and_flash_error(request, message, path="/e_ballots")
Esempio n. 38
0
def enter_judge(request):
    if request.method == "POST":
        form = JudgeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                                                "Judge cannot be validated")
            return redirect_and_flash_success(
                request,
                "Judge {} created successfully".format(
                    form.cleaned_data["name"]),
                path="/")
    else:
        form = JudgeForm(first_entry=True)
    return render(request, "common/data_entry.html", {
        "form": form,
        "title": "Create Judge"
    })
Esempio n. 39
0
def enter_team(request):
    if request.method == 'POST':
        form = TeamEntryForm(request.POST)
        if form.is_valid():
            try:
                team = form.save()
            except ValueError:
                return redirect_and_flash_error(request,
                        "Team name cannot be validated, most likely a duplicate school")
            num_forms = form.cleaned_data['number_scratches']
            if num_forms > 0:
                return HttpResponseRedirect('/team/'+str(team.pk)+'/scratches/add/'+str(num_forms))
            else:
                return redirect_and_flash_success(request,
                        "Team {} created successfully".format(team.name),
                        path="/")
    else:
        form = TeamEntryForm()
    return render(request, 'common/data_entry.html',
                             {'form': form, 'title': "Create Team"})
Esempio n. 40
0
def view_scratches(request, judge_id):
    try:
        judge_id = int(judge_id)
    except ValueError:
        return redirect_and_flash_error(request, "Received invalid data")
    scratches = Scratch.objects.filter(judge=judge_id)
    judge = Judge.objects.get(pk=judge_id)
    number_scratches = len(scratches)
    if request.method == "POST":
        forms = [
            ScratchForm(request.POST, prefix=str(i), instance=scratches[i - 1])
            for i in range(1, number_scratches + 1)
        ]
        all_good = True
        for form in forms:
            all_good = all_good and form.is_valid()
        if all_good:
            for form in forms:
                form.save()
            return redirect_and_flash_success(
                request, "Scratches created successfully")
    else:
        forms = [
            ScratchForm(prefix=str(i), instance=scratches[i - 1])
            for i in range(1,
                           len(scratches) + 1)
        ]
    delete_links = [
        "/judge/" + str(judge_id) + "/scratches/delete/" + str(scratches[i].id)
        for i in range(len(scratches))
    ]
    links = [("/judge/" + str(judge_id) + "/scratches/add/1/", "Add Scratch")]

    return render(
        request, "common/data_entry_multiple.html", {
            "forms": list(zip(forms, delete_links)),
            "data_type": "Scratch",
            "links": links,
            "title": "Viewing Scratch Information for %s" % (judge.name)
        })
Esempio n. 41
0
def enter_room(request):
    if request.method == "POST":
        form = RoomForm(request.POST)
        if form.is_valid():
            try:
                form.save()
            except ValueError:
                return redirect_and_flash_error(
                    request,
                    "Room name cannot be validated, most likely a duplicate room"
                )
            return redirect_and_flash_success(
                request,
                "Room {} created successfully".format(
                    form.cleaned_data["name"]),
                path="/")
    else:
        form = RoomForm()
    return render(request, "common/data_entry.html", {
        "form": form,
        "title": "Create Room"
    })
Esempio n. 42
0
def pair_round(request):
    cache_logic.clear_cache()
    current_round = TabSettings.objects.get(key="cur_round")
    current_round_number = current_round.value
    if request.method == "POST":
        # We should pair the round
        try:
            TabSettings.set("pairing_released", 0)
            backup.backup_round("round_%i_before_pairing" %
                                (current_round_number))

            with transaction.atomic():
                tab_logic.pair_round()
                current_round.value = current_round.value + 1
                current_round.save()
        except Exception as exp:
            emit_current_exception()
            return redirect_and_flash_error(
                request,
                "Could not pair next round, got error: {}".format(exp))
        return view_status(request)
    else:
        # See if we can pair the round
        title = "Pairing Round %s" % (current_round_number)
        check_status = []

        judges = tab_logic.have_enough_judges(current_round_number)
        rooms = tab_logic.have_enough_rooms(current_round_number)

        msg = "N/2 Judges checked in for Round {0}? Need {1}, have {2}".format(
            current_round_number, judges[1][1], judges[1][0])
        if judges[0]:
            check_status.append((msg, "Yes", "Judges are checked in"))
        else:
            check_status.append((msg, "No", "Not enough judges"))

        msg = "N/2 Rooms available Round {0}? Need {1}, have {2}".format(
            current_round_number, rooms[1][1], rooms[1][0])
        if rooms[0]:
            check_status.append((msg, "Yes", "Rooms are checked in"))
        else:
            check_status.append((msg, "No", "Not enough rooms"))

        msg = "All Rounds properly entered for Round %s" % (
            current_round_number - 1)
        ready_to_pair = "Yes"
        ready_to_pair_alt = "Checks passed!"
        try:
            tab_logic.have_properly_entered_data(current_round_number)
            check_status.append((msg, "Yes", "All rounds look good"))
        except PrevRoundNotEnteredError as e:
            ready_to_pair = "No"
            ready_to_pair_alt = str(e)
            check_status.append(
                (msg, "No", "Not all rounds are entered. %s" % str(e)))
        except ByeAssignmentError as e:
            ready_to_pair = "No"
            ready_to_pair_alt = str(e)
            check_status.append(
                (msg, "No", "You have a bye and results. %s" % str(e)))
        except NoShowAssignmentError as e:
            ready_to_pair = "No"
            ready_to_pair_alt = str(e)
            check_status.append(
                (msg, "No", "You have a noshow and results. %s" % str(e)))

        return render(request, "pairing/pair_round.html", locals())
Esempio n. 43
0
def outround_pairing_view(request,
                          type_of_round=BreakingTeam.VARSITY,
                          num_teams=None):

    choice = TabSettings.get("choice", 0)

    if num_teams is None:
        num_teams = TabSettings.get("var_teams_to_break", 8)

        while not math.log(num_teams, 2) % 1 == 0:
            num_teams += 1

        return redirect("outround_pairing_view",
                        type_of_round=BreakingTeam.VARSITY,
                        num_teams=num_teams)

    pairing_released = False

    if type_of_round == BreakingTeam.VARSITY:
        pairing_released = TabSettings.get("var_teams_visible",
                                           256) <= num_teams
    elif type_of_round == BreakingTeam.NOVICE:
        pairing_released = TabSettings.get("nov_teams_visible",
                                           256) <= num_teams

    label = "[%s] Ro%s" % ("V" if type_of_round == BreakingTeam.VARSITY else
                           "N", num_teams)
    nov_teams_to_break = TabSettings.get("nov_teams_to_break")
    var_teams_to_break = TabSettings.get("var_teams_to_break")

    if not nov_teams_to_break or not var_teams_to_break:
        return redirect_and_flash_error(request,
                                        "Please check your break tab settings",
                                        path="/")

    outround_options = get_outround_options(var_teams_to_break,
                                            nov_teams_to_break)

    outrounds = Outround.objects.filter(type_of_round=type_of_round,
                                        num_teams=num_teams).all()

    judges_per_panel = TabSettings.get("var_panel_size", 3) \
                       if type_of_round == BreakingTeam.VARSITY \
                          else TabSettings.get("nov_panel_size", 3)
    judge_slots = [i for i in range(1, judges_per_panel + 1)]

    var_to_nov = TabSettings.get("var_to_nov", 2)

    var_to_nov = offset_to_quotient(var_to_nov)

    other_round_num = num_teams / var_to_nov
    if type_of_round == BreakingTeam.NOVICE:
        other_round_num = num_teams * var_to_nov

    other_round_type = BreakingTeam.VARSITY \
                       if type_of_round == BreakingTeam.NOVICE \
                          else BreakingTeam.NOVICE

    pairing_exists = len(outrounds) > 0

    lost_outrounds = [t.loser.id for t in Outround.objects.all() if t.loser]

    excluded_teams = BreakingTeam.objects.filter(
        type_of_team=type_of_round).exclude(team__id__in=lost_outrounds)

    excluded_teams = [t.team for t in excluded_teams]

    excluded_teams = [
        t for t in excluded_teams
        if not Outround.objects.filter(type_of_round=type_of_round,
                                       num_teams=num_teams,
                                       gov_team=t).exists()
    ]

    excluded_teams = [
        t for t in excluded_teams
        if not Outround.objects.filter(type_of_round=type_of_round,
                                       num_teams=num_teams,
                                       opp_team=t).exists()
    ]

    excluded_judges = Judge.objects.exclude(
        judges_outrounds__num_teams=num_teams,
        judges_outrounds__type_of_round=type_of_round,
    ).exclude(judges_outrounds__type_of_round=other_round_type,
              judges_outrounds__num_teams=other_round_num).filter(
                  checkin__round_number=0)

    non_checkins = Judge.objects.exclude(
        judges_outrounds__num_teams=num_teams,
        judges_outrounds__type_of_round=type_of_round).exclude(
            judges_outrounds__type_of_round=other_round_type,
            judges_outrounds__num_teams=other_round_num).exclude(
                checkin__round_number=0)

    available_rooms = Room.objects.exclude(
        rooms_outrounds__num_teams=num_teams,
        rooms_outrounds__type_of_round=type_of_round).exclude(
            rooms_outrounds__num_teams=other_round_num,
            rooms_outrounds__type_of_round=other_round_type)

    checked_in_rooms = [
        r.room for r in RoomCheckIn.objects.filter(round_number=0)
    ]
    available_rooms = [r for r in available_rooms if r in checked_in_rooms]

    size = max(
        list(
            map(len, [
                excluded_teams, excluded_judges, non_checkins, available_rooms
            ])))
    # The minimum rank you want to warn on
    warning = 5
    excluded_people = list(
        zip(*[
            x + [""] * (size - len(x)) for x in [
                list(excluded_teams),
                list(excluded_judges),
                list(non_checkins),
                list(available_rooms)
            ]
        ]))

    return render(request, "outrounds/pairing_base.html", locals())
Esempio n. 44
0
def pair_round(request):
    cache_logic.clear_cache()
    current_round = TabSettings.objects.get(key="cur_round")
    current_round_number = current_round.value
    if request.method == 'POST':
        # We should pair the round
        try:
            TabSettings.set('pairing_released', 0)
            backup.backup_round("round_%i_before_pairing" % (current_round_number))

            with transaction.atomic():
                tab_logic.pair_round()
                current_round.value = current_round.value + 1
                current_round.save()
        except Exception as exp:
            emit_current_exception()
            return redirect_and_flash_error(request,
                    "Could not pair next round, got error: {}".format(exp))
        return view_status(request)
    else:
        # See if we can pair the round
        title = "Pairing Round %s" % (current_round_number)
        check_status = []

        judges = tab_logic.have_enough_judges(current_round_number)
        rooms = tab_logic.have_enough_rooms(current_round_number)

        msg = "N/2 Judges checked in for Round {0}? Need {1}, have {2}".format(
              current_round_number, judges[1][1], judges[1][0])
        if judges[0]:
            check_status.append((msg, "Yes", "Judges are checked in"))
        else:
            check_status.append((msg, "No", "Not enough judges"))

        msg = "N/2 Rooms available Round {0}? Need {1}, have {2}".format(
              current_round_number, rooms[1][1], rooms[1][0])
        if rooms[0]:
            check_status.append((msg, "Yes", "Rooms are checked in"))
        else:
            check_status.append((msg, "No", "Not enough rooms"))

        msg = "All Rounds properly entered for Round %s" % (current_round_number - 1)
        ready_to_pair = "Yes"
        ready_to_pair_alt = "Checks passed!"
        try:
            tab_logic.have_properly_entered_data(current_round_number)
            check_status.append((msg, "Yes", "All rounds look good"))
        except PrevRoundNotEnteredError as e:
            ready_to_pair = "No"
            ready_to_pair_alt = str(e)
            check_status.append((msg, "No", "Not all rounds are entered. %s" % str(e)))
        except ByeAssignmentError as e:
            ready_to_pair = "No"
            ready_to_pair_alt = str(e)
            check_status.append((msg, "No", "You have a bye and results. %s" % str(e)))
        except NoShowAssignmentError as e:
            ready_to_pair = "No"
            ready_to_pair_alt = str(e) 
            check_status.append((msg, "No", "You have a noshow and results. %s" % str(e)))

        return render(request, 'pairing/pair_round.html', locals())
Esempio n. 45
0
def tab_card(request, team_id):
    try:
        team_id = int(team_id)
    except ValueError:
        return redirect_and_flash_error(request, "Invalid team id")
    team = Team.objects.get(pk=team_id)
    rounds = ([r for r in Round.objects.filter(gov_team=team)] +
              [r for r in Round.objects.filter(opp_team=team)])
    rounds.sort(key =lambda x: x.round_number)
    roundstats = [RoundStats.objects.filter(round=r) for r in rounds]
    debaters = [d for d in team.debaters.all()]
    iron_man = False
    if (len(debaters) == 1):
      iron_man = True
    d1 = debaters[0]
    if (not iron_man):
      d2 = debaters[1]
    round_stats = []
    num_rounds = TabSettings.objects.get(key="tot_rounds").value
    cur_round = TabSettings.objects.get(key="cur_round").value
    blank = " ";
    for i in range(num_rounds):
        round_stats.append([blank]*7)

    for r in rounds:
        dstat1 = [k for k in RoundStats.objects.filter(debater=d1).filter(round=r).all()]
        dstat2 = []
        if (not iron_man):
          dstat2 = [k for k in RoundStats.objects.filter(debater=d2).filter(round=r).all()]
        blank_rs = RoundStats(debater=d1, round=r, speaks=0, ranks=0)
        while len(dstat1) + len(dstat2) < 2:
            # Something is wrong with our data, but we don't want to crash
            dstat1.append(blank_rs)
        if not dstat2 and not dstat1:
            break
        if not dstat2:
            dstat1,dstat2 = dstat1[0], dstat1[1]
        elif not dstat1:
            dstat1,dstat2 = dstat2[0], dstat2[1]
        else:
            dstat1,dstat2 = dstat1[0], dstat2[0]
        index = r.round_number - 1
        round_stats[index][3] = " - ".join([j.name for j in r.judges.all()])
        round_stats[index][4] = (float(dstat1.speaks), float(dstat1.ranks))
        round_stats[index][5] = (float(dstat2.speaks), float(dstat2.ranks))
        round_stats[index][6] = (float(dstat1.speaks + dstat2.speaks), float(dstat1.ranks + dstat2.ranks))

        if r.gov_team == team:
            round_stats[index][2] = r.opp_team
            round_stats[index][0] = "G"
            if r.victor == 1:
                round_stats[index][1] = "W"
            elif r.victor == 2 :
                round_stats[index][1] = "L"
            elif r.victor == 3:
                round_stats[index][1] = "WF"
            elif r.victor == 4 :
                round_stats[index][1] = "LF"
            elif r.victor == 5 :
                round_stats[index][1] = "AD"
            elif r.victor == 6:
                round_stats[index][1] = "AW"
        elif r.opp_team == team:
            round_stats[index][2] = r.gov_team
            round_stats[index][0] = "O"
            if r.victor == 1:
                round_stats[index][1] = "L"
            elif r.victor == 2 :
                round_stats[index][1] = "W"
            elif r.victor == 3:
                round_stats[index][1] = "LF"
            elif r.victor == 4 :
                round_stats[index][1] = "WF"
            elif r.victor == 5 :
                round_stats[index][1] = "AD"
            elif r.victor == 6:
                round_stats[index][1] = "AW"

    for i in range(cur_round-1):
        if round_stats[i][6] == blank:
            round_stats[i][6] = (0,0)
    for i in range(1,cur_round-1):
        round_stats[i][6] = (round_stats[i][6][0] + round_stats[i-1][6][0],
                             round_stats[i][6][1] + round_stats[i-1][6][1])
    #Error out if we don't have a bye
    try:
        bye_round = Bye.objects.get(bye_team = team).round_number
    except:
        bye_round = None

    #Duplicates Debater 1 for display if Ironman team    
    if (iron_man):
      d2 = d1
    return render(request, 'tab/tab_card.html', 
                             {'team_name': team.name,
                              'team_school': team.school,
                              'debater_1': d1.name,
                              'debater_1_status': Debater.NOVICE_CHOICES[d1.novice_status][1],
                              'debater_2': d2.name,
                              'debater_2_status': Debater.NOVICE_CHOICES[d2.novice_status][1],
                              'round_stats': round_stats,
                              'd1st': tot_speaks_deb(d1),
                              'd1rt': tot_ranks_deb(d1),
                              'd2st': tot_speaks_deb(d2),
                              'd2rt': tot_ranks_deb(d2),
                              'ts': tot_speaks(team),
                              'tr': tot_ranks(team),
                              'bye_round': bye_round})
Esempio n. 46
0
def tab_card(request, team_id):
    try:
        team_id = int(team_id)
    except ValueError:
        return redirect_and_flash_error(request, "Invalid team id")
    team = Team.objects.get(pk=team_id)
    rounds = ([r for r in Round.objects.filter(gov_team=team)] +
              [r for r in Round.objects.filter(opp_team=team)])
    rounds.sort(key=lambda x: x.round_number)
    debaters = [d for d in team.debaters.all()]
    iron_man = False
    if len(debaters) == 1:
        iron_man = True
    deb1 = debaters[0]
    if not iron_man:
        deb2 = debaters[1]
    round_stats = []
    num_rounds = TabSettings.objects.get(key="tot_rounds").value
    cur_round = TabSettings.objects.get(key="cur_round").value
    blank = " "
    for i in range(num_rounds):
        round_stats.append([blank] * 7)

    for round_obj in rounds:
        dstat1 = [
            k for k in RoundStats.objects.filter(debater=deb1).filter(
                round=round_obj).all()
        ]
        dstat2 = []
        if not iron_man:
            dstat2 = [
                k for k in RoundStats.objects.filter(debater=deb2).filter(
                    round=round_obj).all()
            ]
        blank_rs = RoundStats(debater=deb1, round=round_obj, speaks=0, ranks=0)
        while len(dstat1) + len(dstat2) < 2:
            # Something is wrong with our data, but we don't want to crash
            dstat1.append(blank_rs)
        if not dstat2 and not dstat1:
            break
        if not dstat2:
            dstat1, dstat2 = dstat1[0], dstat1[1]
        elif not dstat1:
            dstat1, dstat2 = dstat2[0], dstat2[1]
        else:
            dstat1, dstat2 = dstat1[0], dstat2[0]
        index = round_obj.round_number - 1
        round_stats[index][3] = " - ".join(
            [j.name for j in round_obj.judges.all()])
        round_stats[index][4] = (float(dstat1.speaks), float(dstat1.ranks))
        round_stats[index][5] = (float(dstat2.speaks), float(dstat2.ranks))
        round_stats[index][6] = (float(dstat1.speaks + dstat2.speaks),
                                 float(dstat1.ranks + dstat2.ranks))

        if round_obj.gov_team == team:
            round_stats[index][2] = round_obj.opp_team
            round_stats[index][0] = "G"
            if round_obj.victor == 1:
                round_stats[index][1] = "W"
            elif round_obj.victor == 2:
                round_stats[index][1] = "L"
            elif round_obj.victor == 3:
                round_stats[index][1] = "WF"
            elif round_obj.victor == 4:
                round_stats[index][1] = "LF"
            elif round_obj.victor == 5:
                round_stats[index][1] = "AD"
            elif round_obj.victor == 6:
                round_stats[index][1] = "AW"
        elif round_obj.opp_team == team:
            round_stats[index][2] = round_obj.gov_team
            round_stats[index][0] = "O"
            if round_obj.victor == 1:
                round_stats[index][1] = "L"
            elif round_obj.victor == 2:
                round_stats[index][1] = "W"
            elif round_obj.victor == 3:
                round_stats[index][1] = "LF"
            elif round_obj.victor == 4:
                round_stats[index][1] = "WF"
            elif round_obj.victor == 5:
                round_stats[index][1] = "AD"
            elif round_obj.victor == 6:
                round_stats[index][1] = "AW"

    for i in range(cur_round - 1):
        if round_stats[i][6] == blank:
            round_stats[i][6] = (0, 0)
    for i in range(1, cur_round - 1):
        round_stats[i][6] = (round_stats[i][6][0] + round_stats[i - 1][6][0],
                             round_stats[i][6][1] + round_stats[i - 1][6][1])
    #Error out if we don't have a bye
    try:
        bye_round = Bye.objects.get(bye_team=team).round_number
    except Exception:
        bye_round = None

    #Duplicates Debater 1 for display if Ironman team
    if iron_man:
        deb2 = deb1
    return render(
        request, "tab/tab_card.html", {
            "team_name": team.display_backend,
            "team_school": team.school,
            "debater_1": deb1.name,
            "debater_1_status": Debater.NOVICE_CHOICES[deb1.novice_status][1],
            "debater_2": deb2.name,
            "debater_2_status": Debater.NOVICE_CHOICES[deb2.novice_status][1],
            "round_stats": round_stats,
            "d1st": tot_speaks_deb(deb1),
            "d1rt": tot_ranks_deb(deb1),
            "d2st": tot_speaks_deb(deb2),
            "d2rt": tot_ranks_deb(deb2),
            "ts": tot_speaks(team),
            "tr": tot_ranks(team),
            "bye_round": bye_round
        })