Rename TeamState to TeamScore

clubs
Laurent 2 years ago
parent aaf75caf3d
commit 7c09d560cd
  1. 12
      padelclub_backend/settings.py
  2. 4
      padelclub_backend/urls.py
  3. 201
      static/admin/js/actions.js
  4. 4
      tournaments/admin.py
  5. 30
      tournaments/migrations/0015_teamscore_delete_teamstate.py
  6. 66
      tournaments/models.py
  7. 168
      tournaments/serializers.py
  8. 1
      tournaments/urls.py
  9. 23
      tournaments/views.py

@ -129,18 +129,6 @@ STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Rest Framework configuration
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
# 'DEFAULT_PERMISSION_CLASSES': [
# 'rest_framework.permissions.IsAuthenticated',
# ],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
]
}
from .settings_local import * from .settings_local import *
from .settings_app import * from .settings_app import *

@ -27,10 +27,10 @@ router.register(r'tournaments', views.TournamentViewSet)
router.register(r'events', views.EventViewSet) router.register(r'events', views.EventViewSet)
router.register(r'group-stages', views.GroupStageViewSet) router.register(r'group-stages', views.GroupStageViewSet)
router.register(r'matches', views.MatchViewSet) router.register(r'matches', views.MatchViewSet)
router.register(r'team-states', views.TeamStateViewSet) router.register(r'team-scores', views.TeamScoreViewSet)
router.register(r'team-registrations', views.TeamRegistrationViewSet) router.register(r'team-registrations', views.TeamRegistrationViewSet)
router.register(r'player-registrations', views.PlayerRegistrationViewSet) router.register(r'player-registrations', views.PlayerRegistrationViewSet)
router.register(r'exp-tournaments', views.ExpandedTournamentViewSet, basename='tournaments-json') # router.register(r'exp-tournaments', views.ExpandedTournamentViewSet, basename='tournaments-json')
urlpatterns = [ urlpatterns = [
path('api/', include(router.urls)), path('api/', include(router.urls)),

@ -1,201 +0,0 @@
/*global gettext, interpolate, ngettext*/
'use strict';
{
function show(selector) {
document.querySelectorAll(selector).forEach(function(el) {
el.classList.remove('hidden');
});
}
function hide(selector) {
document.querySelectorAll(selector).forEach(function(el) {
el.classList.add('hidden');
});
}
function showQuestion(options) {
hide(options.acrossClears);
show(options.acrossQuestions);
hide(options.allContainer);
}
function showClear(options) {
show(options.acrossClears);
hide(options.acrossQuestions);
document.querySelector(options.actionContainer).classList.remove(options.selectedClass);
show(options.allContainer);
hide(options.counterContainer);
}
function reset(options) {
hide(options.acrossClears);
hide(options.acrossQuestions);
hide(options.allContainer);
show(options.counterContainer);
}
function clearAcross(options) {
reset(options);
const acrossInputs = document.querySelectorAll(options.acrossInput);
acrossInputs.forEach(function(acrossInput) {
acrossInput.value = 0;
});
document.querySelector(options.actionContainer).classList.remove(options.selectedClass);
}
function checker(actionCheckboxes, options, checked) {
if (checked) {
showQuestion(options);
} else {
reset(options);
}
actionCheckboxes.forEach(function(el) {
el.checked = checked;
el.closest('tr').classList.toggle(options.selectedClass, checked);
});
}
function updateCounter(actionCheckboxes, options) {
const sel = Array.from(actionCheckboxes).filter(function(el) {
return el.checked;
}).length;
const counter = document.querySelector(options.counterContainer);
// data-actions-icnt is defined in the generated HTML
// and contains the total amount of objects in the queryset
const actions_icnt = Number(counter.dataset.actionsIcnt);
counter.textContent = interpolate(
ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), {
sel: sel,
cnt: actions_icnt
}, true);
const allToggle = document.getElementById(options.allToggleId);
allToggle.checked = sel === actionCheckboxes.length;
if (allToggle.checked) {
showQuestion(options);
} else {
clearAcross(options);
}
}
const defaults = {
actionContainer: "div.actions",
counterContainer: "span.action-counter",
allContainer: "div.actions span.all",
acrossInput: "div.actions input.select-across",
acrossQuestions: "div.actions span.question",
acrossClears: "div.actions span.clear",
allToggleId: "action-toggle",
selectedClass: "selected"
};
window.Actions = function(actionCheckboxes, options) {
options = Object.assign({}, defaults, options);
let list_editable_changed = false;
let lastChecked = null;
let shiftPressed = false;
document.addEventListener('keydown', (event) => {
shiftPressed = event.shiftKey;
});
document.addEventListener('keyup', (event) => {
shiftPressed = event.shiftKey;
});
document.getElementById(options.allToggleId).addEventListener('click', function(event) {
checker(actionCheckboxes, options, this.checked);
updateCounter(actionCheckboxes, options);
});
document.querySelectorAll(options.acrossQuestions + " a").forEach(function(el) {
el.addEventListener('click', function(event) {
event.preventDefault();
const acrossInputs = document.querySelectorAll(options.acrossInput);
acrossInputs.forEach(function(acrossInput) {
acrossInput.value = 1;
});
showClear(options);
});
});
document.querySelectorAll(options.acrossClears + " a").forEach(function(el) {
el.addEventListener('click', function(event) {
event.preventDefault();
document.getElementById(options.allToggleId).checked = false;
clearAcross(options);
checker(actionCheckboxes, options, false);
updateCounter(actionCheckboxes, options);
});
});
function affectedCheckboxes(target, withModifier) {
const multiSelect = (lastChecked && withModifier && lastChecked !== target);
if (!multiSelect) {
return [target];
}
const checkboxes = Array.from(actionCheckboxes);
const targetIndex = checkboxes.findIndex(el => el === target);
const lastCheckedIndex = checkboxes.findIndex(el => el === lastChecked);
const startIndex = Math.min(targetIndex, lastCheckedIndex);
const endIndex = Math.max(targetIndex, lastCheckedIndex);
const filtered = checkboxes.filter((el, index) => (startIndex <= index) && (index <= endIndex));
return filtered;
};
Array.from(document.getElementById('result_list').tBodies).forEach(function(el) {
el.addEventListener('change', function(event) {
const target = event.target;
if (target.classList.contains('action-select')) {
const checkboxes = affectedCheckboxes(target, shiftPressed);
checker(checkboxes, options, target.checked);
updateCounter(actionCheckboxes, options);
lastChecked = target;
} else {
list_editable_changed = true;
}
});
});
document.querySelector('#changelist-form button[name=index]').addEventListener('click', function(event) {
if (list_editable_changed) {
const confirmed = confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost."));
if (!confirmed) {
event.preventDefault();
}
}
});
const el = document.querySelector('#changelist-form input[name=_save]');
// The button does not exist if no fields are editable.
if (el) {
el.addEventListener('click', function(event) {
if (document.querySelector('[name=action]').value) {
const text = list_editable_changed
? gettext("You have selected an action, but you haven’t saved your changes to individual fields yet. Please click OK to save. You’ll need to re-run the action.")
: gettext("You have selected an action, and you haven’t made any changes on individual fields. You’re probably looking for the Go button rather than the Save button.");
if (!confirm(text)) {
event.preventDefault();
}
}
});
}
};
// Call function fn when the DOM is loaded and ready. If it is already
// loaded, call the function now.
// http://youmightnotneedjquery.com/#ready
function ready(fn) {
if (document.readyState !== 'loading') {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function() {
const actionsEls = document.querySelectorAll('tr input.action-select');
if (actionsEls.length > 0) {
Actions(actionsEls);
}
});
}

@ -1,5 +1,5 @@
from django.contrib import admin from django.contrib import admin
from .models import Club, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamState, TeamRegistration, PlayerRegistration from .models import Club, TeamScore, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamRegistration, PlayerRegistration
from django.contrib.auth.admin import UserAdmin from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.forms import UserCreationForm, UserChangeForm
@ -30,7 +30,7 @@ admin.site.register(Event)
admin.site.register(Round) admin.site.register(Round)
admin.site.register(GroupStage) admin.site.register(GroupStage)
admin.site.register(Match) admin.site.register(Match)
admin.site.register(TeamState) admin.site.register(TeamScore)
admin.site.register(TeamRegistration) admin.site.register(TeamRegistration)
admin.site.register(Tournament) admin.site.register(Tournament)
admin.site.register(PlayerRegistration) admin.site.register(PlayerRegistration)

@ -0,0 +1,30 @@
# Generated by Django 4.2.11 on 2024-03-09 11:43
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('tournaments', '0014_alter_teamstate_team_registration'),
]
operations = [
migrations.CreateModel(
name='TeamScore',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('score', models.CharField(blank=True, max_length=50, null=True)),
('walk_out', models.IntegerField(blank=True, null=True)),
('lucky_loser', models.BooleanField()),
('match', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='team_scores', to='tournaments.match')),
('player_registrations', models.ManyToManyField(blank=True, to='tournaments.playerregistration')),
('team_registration', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='tournaments.teamregistration')),
],
),
migrations.DeleteModel(
name='TeamState',
),
]

@ -3,7 +3,7 @@ from django.db import models
from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import AbstractUser
from django.conf import settings from django.conf import settings
import uuid import uuid
import os import os, json
from django.utils import timezone from django.utils import timezone
from django.utils.encoding import Promise from django.utils.encoding import Promise
@ -149,14 +149,21 @@ class Tournament(models.Model):
return team_calls return team_calls
# stage_call = StageCall(f"1/{self.index}") def live_matches(self):
# for match in self.match_set.all(): matches = []
# names = map(lambda ts: ts.player_names(), match.teamstate_set.all()) for group_stage in self.group_stage_set:
# if names: for match in group_stage.match_set:
# team_call = TeamCall(names, match.formatted_start_date) matches.append(match)
# stage_call.add_team(team_call) for round in self.round_set:
for match in round.match_set:
matches.append(match)
# return stage_call return map(lambda match: match.live_match(), matches)
# # Convert object attributes to a dictionary
# dict = self.__dict__
# # Convert dictionary to JSON
# return json.dumps(dict)
class Round(models.Model): class Round(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
@ -204,22 +211,13 @@ class GroupStage(models.Model):
def name(self): def name(self):
return f"Poule {self.index}" return f"Poule {self.index}"
# def stage_call(self):
# stage_call = StageCall(f"poule{self.index}")
# for team_registration in self.teamregistration_set.all():
# names = map(lambda pr: pr.name(), team_registration.playerregistration_set.all())
# time = self.next_match(team_registration).start_date.strftime("%H:%M") # "17h45" # which match do we take, the first unfinished?
# team_call = TeamCall(names, time)
# return stage_call
def next_match(self, player_registration): def next_match(self, player_registration):
matches = self.matches_for_registration(player_registration).filter(end_date__isnull=False).order_by('start_date') matches = self.matches_for_registration(player_registration).filter(end_date__isnull=False).order_by('start_date')
return matches[0] return matches[0]
def matches_for_registration(self, player_registration): def matches_for_registration(self, player_registration):
team_states = TeamState.objects.filter(player_registrations=player_registration) team_scores = TeamScore.objects.filter(player_registrations=player_registration)
return map(lambda ts: ts.match, team_states) return map(lambda ts: ts.match, team_scores)
class Match(models.Model): class Match(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
@ -246,7 +244,7 @@ class Match(models.Model):
return f"{str(self.group_stage)} > {desc} > {player_names}" return f"{str(self.group_stage)} > {desc} > {player_names}"
def player_names(self): def player_names(self):
return map(lambda ts: ts.player_names(), self.team_states.all()) return map(lambda ts: ts.player_names(), self.team_scores.all())
def formatted_start_date(self): def formatted_start_date(self):
if self.start_date: if self.start_date:
@ -291,27 +289,17 @@ class Match(models.Model):
livematch = LiveMatch(title, date, duration) livematch = LiveMatch(title, date, duration)
for team_state in self.team_states: for team_state in self.team_scores:
image = team_state.team_registration.logo image = team_state.team_registration.logo
names = team_state.team_names() names = team_state.team_names()
scores = team_state.score scores = team_state.score
weight = team_state.weight weight = team_state.team_registration.weight()
is_winner = False is_winner = team_state.team_registration == self.winning_team_id
team = Team(image, names, scores, weight, is_winner) team = Team(image, names, scores, weight, is_winner)
livematch.add_team(team)
return livematch
break
# def __init__(self, image, names, scores, weight, is_winner):
# def __init__(self, title, date, teams, duration):
class TeamRegistration(models.Model): class TeamRegistration(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
@ -345,7 +333,7 @@ class TeamRegistration(models.Model):
return "no players" return "no players"
def next_stage(self): def next_stage(self):
matches = Match.objects.filter(group_stage__isnull=True, team_states__player_registrations__id=self.id).order_by('round__index') matches = Match.objects.filter(group_stage__isnull=True, team_scores__player_registrations__id=self.id).order_by('round__index')
if matches: if matches:
return matches[0].round.name() return matches[0].round.name()
elif self.group_stage: elif self.group_stage:
@ -377,11 +365,11 @@ class PlayerRegistration(models.Model):
def name(self): def name(self):
return f"{self.first_name} {self.last_name}" return f"{self.first_name} {self.last_name}"
class TeamState(models.Model): class TeamScore(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name="team_states") match = models.ForeignKey(Match, on_delete=models.CASCADE, related_name="team_scores")
player_registrations = models.ManyToManyField(PlayerRegistration, blank=True)
team_registration = models.ForeignKey(TeamRegistration, on_delete=models.CASCADE, null=True, blank=True) team_registration = models.ForeignKey(TeamRegistration, on_delete=models.CASCADE, null=True, blank=True)
player_registrations = models.ManyToManyField(PlayerRegistration, blank=True)
score = models.CharField(max_length=50, null=True, blank=True) score = models.CharField(max_length=50, null=True, blank=True)
walk_out = models.IntegerField(null=True, blank=True) #id, int of the walked_out team walk_out = models.IntegerField(null=True, blank=True) #id, int of the walked_out team
lucky_loser = models.BooleanField() lucky_loser = models.BooleanField()

@ -1,9 +1,9 @@
from rest_framework import serializers from rest_framework import serializers
from .models import Club, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamState, TeamRegistration, PlayerRegistration from .models import Club, TeamScore, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamRegistration, PlayerRegistration
from django.contrib.auth import password_validation from django.contrib.auth import password_validation
from django.utils.translation import gettext_lazy as _ from django.utils.translation import gettext_lazy as _
class UserSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True) password = serializers.CharField(write_only=True)
@ -15,76 +15,76 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
return user return user
class Meta: class Meta:
club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all()) # club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all())
model = CustomUser model = CustomUser
fields = ['id', 'username', 'password', 'club_id', 'umpire_code', 'clubs', 'phone', 'first_name', 'last_name', 'licence_id'] fields = ['id', 'username', 'password', 'club', 'umpire_code', 'clubs', 'phone', 'first_name', 'last_name', 'licence_id']
class ClubSerializer(serializers.HyperlinkedModelSerializer): class ClubSerializer(serializers.ModelSerializer):
class Meta: class Meta:
model = Club model = Club
fields = ['id', 'name', 'acronym', 'phone', 'code', 'federal_club_data', 'address', 'city', 'zip_code', 'latitude', 'longitude'] fields = ['id', 'name', 'acronym', 'phone', 'code', 'federal_club_data', 'address', 'city', 'zip_code', 'latitude', 'longitude']
class TournamentSerializer(serializers.HyperlinkedModelSerializer): class TournamentSerializer(serializers.ModelSerializer):
class Meta: class Meta:
# club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all()) # club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all())
event_id = serializers.PrimaryKeyRelatedField(queryset=Event.objects.all()) # event_id = serializers.PrimaryKeyRelatedField(queryset=Event.objects.all())
creator_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all()) # creator_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all())
model = Tournament model = Tournament
fields = ['id', 'name', 'event_id', 'creator_id', 'start_date', 'end_date', 'creation_date', fields = ['id', 'name', 'event', 'creator', 'start_date', 'end_date', 'creation_date',
'is_private', 'format', 'group_stage_format', 'round_format', 'loser_round_format', 'bracket_sort_mode', 'is_private', 'format', 'group_stage_format', 'round_format', 'loser_round_format', 'bracket_sort_mode',
'group_stage_count', 'rank_source_date', 'day_duration', 'team_count', 'team_sorting', 'group_stage_count', 'rank_source_date', 'day_duration', 'team_count', 'team_sorting',
'federal_category', 'federal_level_category', 'federal_age_category', 'group_stage_court_count', 'federal_category', 'federal_level_category', 'federal_age_category', 'group_stage_court_count',
'seed_count', 'closed_registration_date', 'group_stage_additional_qualified', 'court_count', 'prioritize_club_members', 'seed_count', 'closed_registration_date', 'group_stage_additional_qualified', 'court_count', 'prioritize_club_members',
'qualified_per_group_stage', 'teams_per_group_stage'] 'qualified_per_group_stage', 'teams_per_group_stage']
class EventSerializer(serializers.HyperlinkedModelSerializer): class EventSerializer(serializers.ModelSerializer):
class Meta: class Meta:
club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all()) # club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all())
model = Event model = Event
fields = ['id', 'club_id', 'date', 'name', 'federal_tournament_data', 'court_count', 'tenup_id', fields = ['id', 'club', 'date', 'name', 'federal_tournament_data', 'court_count', 'tenup_id',
'group_stage_format', 'round_format', 'loser_round_format'] 'group_stage_format', 'round_format', 'loser_round_format']
class RoundSerializer(serializers.HyperlinkedModelSerializer): class RoundSerializer(serializers.ModelSerializer):
class Meta: class Meta:
tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all()) # tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all())
loser_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all()) # loser_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all())
model = Round model = Round
fields = ['id', 'index', 'tournament_id', 'loser_id', 'format'] fields = ['id', 'index', 'tournament', 'loser', 'format']
class GroupStageSerializer(serializers.HyperlinkedModelSerializer): class GroupStageSerializer(serializers.ModelSerializer):
class Meta: class Meta:
tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all()) # tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all())
model = GroupStage model = GroupStage
fields = ['id', 'index', 'tournament_id', 'format'] fields = ['id', 'index', 'tournament', 'format']
class MatchSerializer(serializers.HyperlinkedModelSerializer): class MatchSerializer(serializers.ModelSerializer):
class Meta: class Meta:
round_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all()) # round_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all())
group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all()) # group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all())
model = Match model = Match
fields = ['id', 'round_id', 'group_stage_id', 'index', 'format', 'court', 'start_date', 'end_date', fields = ['id', 'round', 'group_stage', 'index', 'format', 'court', 'start_date', 'end_date',
'serving_team_id', 'winning_team_id', 'losing_team_id'] 'serving_team_id', 'winning_team_id', 'losing_team_id']
class TeamStateSerializer(serializers.HyperlinkedModelSerializer): class TeamScoreSerializer(serializers.ModelSerializer):
class Meta: class Meta:
match_id = serializers.PrimaryKeyRelatedField(queryset=Match.objects.all()) # match_id = serializers.PrimaryKeyRelatedField(queryset=Match.objects.all())
model = TeamState model = TeamScore
fields = ['id', 'match_id', 'score', 'walk_out', 'lucky_loser'] fields = ['id', 'match', 'score', 'walk_out', 'lucky_loser']
class TeamRegistrationSerializer(serializers.HyperlinkedModelSerializer): class TeamRegistrationSerializer(serializers.ModelSerializer):
class Meta: class Meta:
match_id = serializers.PrimaryKeyRelatedField(queryset=Match.objects.all()) # match_id = serializers.PrimaryKeyRelatedField(queryset=Match.objects.all())
group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all()) # group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all())
model = TeamRegistration model = TeamRegistration
fields = ['id', 'match_id', 'group_stage_id', 'registration_date', 'call_date', 'initial_position', fields = ['id', 'match', 'group_stage', 'registration_date', 'call_date', 'initial_position',
'group_stage_position', 'logo'] 'group_stage_position', 'logo']
class PlayerRegistrationSerializer(serializers.HyperlinkedModelSerializer): class PlayerRegistrationSerializer(serializers.ModelSerializer):
class Meta: class Meta:
team_registration_id = serializers.PrimaryKeyRelatedField(queryset=TeamRegistration.objects.all()) # team_registration_id = serializers.PrimaryKeyRelatedField(queryset=TeamRegistration.objects.all())
# team_state_id = serializers.PrimaryKeyRelatedField(queryset=TeamState.objects.all()) # team_state_id = serializers.PrimaryKeyRelatedField(queryset=TeamState.objects.all())
model = PlayerRegistration model = PlayerRegistration
fields = ['id', 'team_registration_id', 'first_name', 'last_name', 'licence_id', 'rank', 'has_paid'] fields = ['id', 'team_registration', 'first_name', 'last_name', 'licence_id', 'rank', 'has_paid']
class ChangePasswordSerializer(serializers.Serializer): class ChangePasswordSerializer(serializers.Serializer):
old_password = serializers.CharField(max_length=128, write_only=True, required=True) old_password = serializers.CharField(max_length=128, write_only=True, required=True)
@ -112,53 +112,53 @@ class ChangePasswordSerializer(serializers.Serializer):
user.save() user.save()
return user return user
class ExpandedMatchSerializer(serializers.HyperlinkedModelSerializer): # class ExpandedMatchSerializer(serializers.ModelSerializer):
team_states = TeamStateSerializer(many=True, read_only=True) # team_states = TeamScoreSerializer(many=True, read_only=True)
class Meta: # class Meta:
round_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all()) # round_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all())
group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all()) # group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all())
model = Match # model = Match
fields = ['id', 'round_id', 'group_stage_id', 'index', 'format', 'court', 'start_date', 'end_date', # fields = ['id', 'round_id', 'group_stage_id', 'index', 'format', 'court', 'start_date', 'end_date',
'serving_team_id', 'winning_team_id', 'losing_team_id', 'team_states'] # 'serving_team_id', 'winning_team_id', 'losing_team_id', 'team_states']
class ExpandedRoundSerializer(serializers.HyperlinkedModelSerializer): # class ExpandedRoundSerializer(serializers.ModelSerializer):
match_set = ExpandedMatchSerializer(many=True, read_only=True) # match_set = ExpandedMatchSerializer(many=True, read_only=True)
class Meta: # class Meta:
tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all()) # tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all())
loser_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all()) # loser_id = serializers.PrimaryKeyRelatedField(queryset=Round.objects.all())
model = Round # model = Round
fields = ['id', 'index', 'tournament_id', 'loser_id', 'format', 'match_set'] # fields = ['id', 'index', 'tournament_id', 'loser_id', 'format', 'match_set']
class ExpandedGroupStageSerializer(serializers.HyperlinkedModelSerializer): # class ExpandedGroupStageSerializer(serializers.ModelSerializer):
match_set = ExpandedMatchSerializer(many=True, read_only=True) # match_set = ExpandedMatchSerializer(many=True, read_only=True)
class Meta: # class Meta:
tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all()) # tournament_id = serializers.PrimaryKeyRelatedField(queryset=Tournament.objects.all())
model = GroupStage # model = GroupStage
fields = ['id', 'index', 'tournament_id', 'format', 'match_set'] # fields = ['id', 'index', 'tournament_id', 'format', 'match_set']
class ExpandedTeamRegistrationSerializer(serializers.HyperlinkedModelSerializer): # class ExpandedTeamRegistrationSerializer(serializers.ModelSerializer):
playerregistration_set = PlayerRegistrationSerializer(many=True, read_only=True) # playerregistration_set = PlayerRegistrationSerializer(many=True, read_only=True)
call_date = serializers.DateTimeField(format='%H:%M') # call_date = serializers.DateTimeField(format='%H:%M')
class Meta: # class Meta:
# match_id = serializers.PrimaryKeyRelatedField(queryset=Match.objects.all()) # # match_id = serializers.PrimaryKeyRelatedField(queryset=Match.objects.all())
group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all()) # group_stage_id = serializers.PrimaryKeyRelatedField(queryset=GroupStage.objects.all())
model = TeamRegistration # model = TeamRegistration
fields = ['id', 'group_stage_id', 'registration_date', 'call_date', 'initial_position', # fields = ['id', 'group_stage_id', 'registration_date', 'call_date', 'initial_position',
'group_stage_position', 'logo', 'playerregistration_set'] # 'group_stage_position', 'logo', 'playerregistration_set']
class ExpandedTournamentSerializer(serializers.HyperlinkedModelSerializer): # class ExpandedTournamentSerializer(serializers.ModelSerializer):
teamregistration_set = ExpandedTeamRegistrationSerializer(many=True, read_only=True) # teamregistration_set = ExpandedTeamRegistrationSerializer(many=True, read_only=True)
round_set = ExpandedRoundSerializer(many=True, read_only=True) # round_set = ExpandedRoundSerializer(many=True, read_only=True)
groupstage_set = ExpandedGroupStageSerializer(many=True, read_only=True) # groupstage_set = ExpandedGroupStageSerializer(many=True, read_only=True)
class Meta: # class Meta:
# club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all()) # # club_id = serializers.PrimaryKeyRelatedField(queryset=Club.objects.all())
event_id = serializers.PrimaryKeyRelatedField(queryset=Event.objects.all()) # event_id = serializers.PrimaryKeyRelatedField(queryset=Event.objects.all())
creator_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all()) # creator_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all())
model = Tournament # model = Tournament
fields = ['id', 'name', 'event_id', 'creator_id', 'start_date', 'end_date', 'creation_date', # fields = ['id', 'name', 'event_id', 'creator_id', 'start_date', 'end_date', 'creation_date',
'is_private', 'format', 'group_stage_format', 'round_format', 'loser_round_format', 'bracket_sort_mode', # 'is_private', 'format', 'group_stage_format', 'round_format', 'loser_round_format', 'bracket_sort_mode',
'group_stage_count', 'rank_source_date', 'day_duration', 'team_count', 'team_sorting', # 'group_stage_count', 'rank_source_date', 'day_duration', 'team_count', 'team_sorting',
'federal_category', 'federal_level_category', 'federal_age_category', 'group_stage_court_count', # 'federal_category', 'federal_level_category', 'federal_age_category', 'group_stage_court_count',
'seed_count', 'closed_registration_date', 'group_stage_additional_qualified', 'court_count', 'prioritize_club_members', # 'seed_count', 'closed_registration_date', 'group_stage_additional_qualified', 'court_count', 'prioritize_club_members',
'qualified_per_group_stage', 'teams_per_group_stage', 'teamregistration_set', 'round_set', 'groupstage_set'] # 'qualified_per_group_stage', 'teams_per_group_stage', 'teamregistration_set', 'round_set', 'groupstage_set']

@ -6,4 +6,5 @@ urlpatterns = [
path("", views.index, name="index"), path("", views.index, name="index"),
path('tournament/<str:tournament_id>/', views.tournament, name='tournament'), path('tournament/<str:tournament_id>/', views.tournament, name='tournament'),
path('tournament/<str:tournament_id>/planning/', views.tournament_planning, name='tournament-planning'), path('tournament/<str:tournament_id>/planning/', views.tournament_planning, name='tournament-planning'),
path('tournament/<str:tournament_id>/json/', views.tournament_json, name='tournament-json'),
] ]

@ -1,7 +1,7 @@
from django.shortcuts import render, get_object_or_404 from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse from django.http import HttpResponse
from .serializers import ClubSerializer, TournamentSerializer, ExpandedTournamentSerializer, UserSerializer, ChangePasswordSerializer, EventSerializer, RoundSerializer, GroupStageSerializer, MatchSerializer, TeamStateSerializer, TeamRegistrationSerializer, PlayerRegistrationSerializer from .serializers import ClubSerializer, TournamentSerializer, UserSerializer, ChangePasswordSerializer, EventSerializer, RoundSerializer, GroupStageSerializer, MatchSerializer, TeamScoreSerializer, TeamRegistrationSerializer, PlayerRegistrationSerializer
from .models import Club, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamState, TeamRegistration, PlayerRegistration from .models import Club, Tournament, CustomUser, Event, Round, GroupStage, Match, TeamScore, TeamRegistration, PlayerRegistration
from .models import TeamCall from .models import TeamCall
from rest_framework import viewsets, permissions from rest_framework import viewsets, permissions
@ -12,6 +12,7 @@ from rest_framework import status
from rest_framework.generics import UpdateAPIView from rest_framework.generics import UpdateAPIView
from django.template import loader from django.template import loader
from datetime import date from datetime import date
from django.http import JsonResponse
def index(request): def index(request):
today = date.today() today = date.today()
@ -65,6 +66,12 @@ def tournament_planning(request, tournament_id):
return HttpResponse(template.render(context, request)) return HttpResponse(template.render(context, request))
def tournament_json(request, tournament_id):
tournament = get_object_or_404(Tournament, pk=tournament_id)
live_matches = tournament.live_matches()
return JsonResponse(live_matches.__dict__)
# def index(request): # def index(request):
# club = Club.objects.first() # club = Club.objects.first()
# live_matches = Match.objects.filter(enddate__isnull=True).order_by('court') # live_matches = Match.objects.filter(enddate__isnull=True).order_by('court')
@ -98,9 +105,9 @@ class TournamentViewSet(viewsets.ModelViewSet):
queryset = Tournament.objects.all() queryset = Tournament.objects.all()
serializer_class = TournamentSerializer serializer_class = TournamentSerializer
class ExpandedTournamentViewSet(viewsets.ModelViewSet): # class ExpandedTournamentViewSet(viewsets.ModelViewSet):
queryset = Tournament.objects.all() # queryset = Tournament.objects.all()
serializer_class = ExpandedTournamentSerializer # serializer_class = ExpandedTournamentSerializer
class ChangePasswordView(UpdateAPIView): class ChangePasswordView(UpdateAPIView):
serializer_class = ChangePasswordSerializer serializer_class = ChangePasswordSerializer
@ -132,9 +139,9 @@ class MatchViewSet(viewsets.ModelViewSet):
queryset = Match.objects.all() queryset = Match.objects.all()
serializer_class = MatchSerializer serializer_class = MatchSerializer
class TeamStateViewSet(viewsets.ModelViewSet): class TeamScoreViewSet(viewsets.ModelViewSet):
queryset = TeamState.objects.all() queryset = TeamScore.objects.all()
serializer_class = TeamStateSerializer serializer_class = TeamScoreSerializer
class TeamRegistrationViewSet(viewsets.ModelViewSet): class TeamRegistrationViewSet(viewsets.ModelViewSet):
queryset = TeamRegistration.objects.all() queryset = TeamRegistration.objects.all()

Loading…
Cancel
Save