def create_league(): admin = g.player form = CreateLeagueForm() if form.validate_on_submit(): league = League(form.name.data, admin, int(form.match_type.data)) if int(form.match_type.data) == TEAM: league.num_teams = int(form.num_teams.data) league.team_size = int(form.team_size.data) else: raise ValueError("Invalid Match Type!") db.session.add(league) db.session.commit() return redirect(url_for('index')) return render_template("create_league.html", form = form)
def DoPost(self): league_name = escape(self.request.get('name')) if len(league_name) > 15: raise Exception("A league name can be no more thn 15 characters long.") league_rules = escape(self.request.get('rules')) if len(league_rules) > 700: raise Exception("A league rulebook can be no more than 700 characters long,\ ideally with link to another page on the interwebz.") league_logo = escape(self.request.get('logo')) if len(league_logo) > 150: raise Exception("A league logo is a uri to an icon, no more than 150 characters long.") league = League(name = league_name, rules = league_rules, logo = league_logo) league.put() logging.info("Creating new league %s" % (league)) self.redirect('/')
def main(args): league = League(args[1]) teams = league.get_members() set_size = 2 schedule = set() teamrange = range(len(teams)) for comb in itertools.product(teamrange, repeat=set_size): comb = sorted(list(comb)) if len(set(comb)) == set_size: schedule.add(tuple(comb)) schedule = list(schedule) random.shuffle(schedule) print schedule
def get_data(): check_logos_directory() for i in range(1929, 2021): print("Getting year", i) league = League(i, handle_jornada(i)) league_to_csv(league) time.sleep(5)
def _leagues_data(): _leagues = League.get_all() if len(_leagues) == 0: sentry.captureMessage('Leagues.get_all() returned an empty list.') return [] replay_counts = {x.league_id: x.count for x in db.engine.execute( text(""" SELECT r.league_id as league_id, count(*) as count FROM {replay_table} r WHERE r.league_id in ({league_id_csv}) AND r.state = "ARCHIVED" GROUP BY r.league_id """.format(replay_table=Replay.__tablename__, league_id_csv=",".join(str(x.id) for x in _leagues)) ) )} leagues_with_replays = [] for _league in _leagues: if replay_counts.get(_league.id) > 0: _league.count = replay_counts.get(_league.id) leagues_with_replays.append(_league) # Sort by archived count return sorted(leagues_with_replays, key=lambda r: r.count, reverse=True)
def league(_id, view=None, page=1): _league = League.get_by_id(_id) _view = None if _league is None: abort(404) if view is None: _replays = Replay.query.filter(Replay.league_id == _id).\ order_by(Replay.id.desc()).\ paginate(page, current_app.config["REPLAYS_PER_PAGE"], False) else: try: _view = LeagueView.query.filter(LeagueView.id == view, LeagueView.league_id == _id).one() except NoResultFound: abort(404) _replays = Replay.query.filter(Replay.league_id == _id, *_view.get_filters()).\ order_by(Replay.id.desc()).\ paginate(page, current_app.config["REPLAYS_PER_PAGE"], False) # Get all views views = LeagueView.query.filter(LeagueView.league_id == _id).all() return render_template("leagues/league.html", title=u"{} - Dotabank".format(_league.name), meta_description=u"Replays archived for {}; {} ...".format(_league.name, _league.short_description), league=_league, replays=_replays, current_view=_view, page=page, views=views)
def create_league(): # must be signed in if 'user_id' not in session: return redirect(url_for('signin')) # registration form league = CreateLeague() if request.method == 'POST': if league.validate() == False: return render_template('create_league.html', form=league) else: try: # write league to database newLeague = League(league.league_name.data, league.league_pwd.data, int(session['user_id'])) db.session.add(newLeague) db.session.commit() lid = League.query.filter_by(league_name=league.league_name.data).first() # add users addUser = LeagueUser(lid.league_id, int(session['user_id'])) db.session.add(addUser) db.session.commit() return redirect(url_for('index')) except: e = list(league.league_name.errors) e.append('This league already exists.') league.email.errors = tuple(e) return render_template('create_league.html', form=league) elif request.method == 'GET': return render_template("create_league.html", form=league)
def DoGet(self): additional_values = { 'active_leagues': League.all_active().fetch(5,0) #just the first 5 leagues } self.template_values.update(additional_values) self.render_to_response("index.html")
def update_leauges(): _updated_key = 'league_info_updated' _lock_key = 'league_info_update_lock' # If the last-updated key has expired, and the lock is not set (the lock will be set if another request # beat this one to the job) if not mem_cache.get(_updated_key) and not mem_cache.get(_lock_key): # Set lock before doing expensive task. mem_cache.set(_lock_key, True, timeout=current_app.config['UPDATE_LEAGUES_TIMEOUT']) # Timeout in case the app crashes before it releases the lock. # Update hero data League.update_leagues_from_webapi() # Set key to say we've updated the data. We'll re-run this process when this key expires mem_cache.set(_updated_key, True, timeout=current_app.config['UPDATE_LEAGUES_TIMEOUT']) # 1 hour timeout # Release the lock mem_cache.delete(_lock_key)
def get_league(): for page_id in range(1, 2): try: url = CK_API_URL.format('leagues') response = get_request(url) for league_data in response: try: return DB.open().query(League).filter(League.api_url == league_data['api']).one() except: obj = get_request(league_data['api']) if 'id' in obj: league = League() league.parse_json(obj) DB.save(league) if league: print('SAVED LEAGUE ID {}'.format(league.id)) print('+++++++++++++++++') except: pass
def __init__(self): self.players = pd.DataFrame(list(Player.select().dicts())) self.country = pd.DataFrame(list(Country.select().dicts())) self.league = pd.DataFrame(list(League.select().dicts())) self.team = pd.DataFrame(list(Team.select().dicts())) self.match = pd.DataFrame(list(Match.select().dicts())) self.player_attributes = pd.DataFrame( list(PlayerAttributes.select().dicts())) self.team_attributes = pd.DataFrame( list(TeamAttributes.select().dicts())) self.preprocess()
def import_league_data(csv_file): with open(csv_file) as csv_file: reader = csv.DictReader(csv_file) try: for row in reader: league = League(name=row['Name'], display_name=row['DisplayName']) db.session.add(league) db.session.commit() except: print("Error")
def league(_id, page=1): _league = League.get_by_id(_id) if _league is None: abort(404) _replays = Replay.query.filter(Replay.league_id == _id).paginate(page, current_app.config["REPLAYS_PER_PAGE"], False) return render_template("leagues/league.html", title="{} - Dotabank".format(_league.name), league=_league, replays=_replays)
def league_create_post(): league_name = request.form.get('league_name') credit = request.form.get('credit') if current_user.is_admin_user(): if not credit.isdigit(): flash('Invalid credit value', 'error') return redirect(url_for('admin.index')) new_league = League(name=league_name, credit=credit, state='new') db.session.add(new_league) db.session.commit() flash('League %s created successfully!' % league_name, 'success') return redirect(url_for('admin.index')) else: flash('User is not an admin', 'error') return redirect(url_for('main.profile'))
def get_league(self, key): tree = self._make_req('league/%s' % key) league = tree.find(".//yh:league", self._ns) league_data = { 'id': int(league.find('./yh:league_id', self._ns).text), 'key': league.find('./yh:league_key', self._ns).text, 'name': league.find('./yh:name', self._ns).text, 'season': league.find('./yh:season', self._ns).text, 'current_week': int(league.find('./yh:current_week', self._ns).text), 'is_finished': league.find('./yh:is_finished', self._ns) is not None } return League.update_or_create(_id=league_data['id'], key=league_data['key'], defaults=league_data)[0]
def create_league(request, universe_id, name, level, nbr_div=0): universe = Universe.objects.get(id=universe_id) year = Year.objects.get(universe=universe,current_year=True) universe_teams = Team.objects.filter(universe=universe) placed_teams = LeagueMembership.objects.filter(universe=universe, year=year) available_teams = list(set(universe_teams) - set(placed_teams)) available_teams = sorted(available_teams,key=operator.attrgetter('city.division')) divisions = create_divisions(available_teams, int(nbr_div)) nbr_conf = len(divisions) / 2 conferences = [[] for x in xrange(nbr_conf)] c = 0 for division in divisions: conferences[c].append(division) if c+1 == len(conferences): c = 0 else: c += 1 league = League(universe=universe, name=name, level=level) league.save() conf_nbr=0 for conference in conferences: div_nbr=0 for division in conference: for team in division: lm = LeagueMembership(universe=universe, year=year, league=league, team=team, conference=conf_nbr, division=div_nbr) lm.save() div_nbr+=1 conf_nbr+=1 league.number_playoff_teams = randint((div_nbr+1),(len(available_teams)/2)) league.save() draft_players(universe) create_schedule(league) play_season(league) play_playoffs(league) return HttpResponse("Created league %s." % name)
def _json_to_league(data): league = League(data[LEAGUENAME_LABEL]) jsonroster = data[TEAMROSTER_LABEL] for jsonteam in jsonroster: team = _json_to_team(jsonteam) league.add_team(team) draft_class = None if(data[L_DRAFT_CLASS_LABEL]!= None): draft_class = _json_to_draft_class(data[L_DRAFT_CLASS_LABEL]) league.draft_class = draft_class league.picks_added = data[L_PICKS_ADDED_LABEL] return league
def get_leagues(self): url = "http://footyroom.com/" r = requests.get(url) soup = BeautifulSoup(r.content, "lxml") if r.status_code != 200: error("Failed to process url!") return False # Get main content hodlder main_section = soup.find("section", {"class": "all-leagues-content"}) debug("main_section: {}".format(main_section != None)) # Get children league_group = main_section.find_all("div", recursive=False) other_league_groups = main_section.find_all("section", recursive=False) # debug("main_children: {}".format(match_children != None)) leagues_to_rtn = [] for lg_group in league_group: # Get ul inside div lst = lg_group.find("ul") # Get country from first li of ul country_li = lst.find("li", {"class": "all-leagues-header"}) country = country_li.text leagues = lst.find_all("li", {"class": ""}) for league_li in leagues: league = League(country, league_li.text) url = league_li.find("a")["href"] # self.process_league(league, url) leagues_to_rtn.append((league, url)) # Find leagues return leagues_to_rtn
def createLeague(): """Create a new League""" # If method is POST if request.method == 'POST': # Create an SEO friendly slug for the new league slug = slugify(request.form['name']) # Check if a league exists with this slug league = session.query(League).filter_by(slug=slug).first() if league is not None: flash("A league with this name already exists.") return redirect(url_for('createLeague')) # Create a new League league = League(name=request.form['name'], user_id=login_session['user_id']) session.add(league) session.commit() flash("Successfully created new league: {}".format(league.name)) return redirect(url_for('showLeague', league_id=league.slug)) # Show create league template return render_template('create_league.html')
def DoGet(self, league_key_name): league_to_show = League.get_by_id(long(league_key_name)) league_name = league_to_show.name logging.debug('Getting league %s' % league_to_show) self.user = users.get_current_user() # Creates a player if one does not already exist. No signup required! self.player = Player.get_or_insert(self.user.user_id(), user = self.user, pseudonym = self.user.nickname(), league = league_to_show) logging.info('creating player for user %s in league %s' % (self.player.pseudonym, league_name)) if not league_to_show: self.error(404) self.response.out.write("""<strong>No League with key %s. Try looking through the <a href="/">list of leagues</a>.</strong>""" % league_name) additional_values = { 'league_to_show' : league_to_show, 'players' : league_to_show.players(), } self.template_values.update(additional_values) self.render_to_response("league.html")
def get_user_leagues(self): tree = self._make_req('users;use_login=1/games;game_key=nfl/leagues') league_data = [{ 'id': int(league.find('./yh:league_id', self._ns).text), 'key': league.find('./yh:league_key', self._ns).text, 'name': league.find('./yh:name', self._ns).text, 'season': league.find('./yh:season', self._ns).text, 'current_week': int(league.find('./yh:current_week', self._ns).text), 'is_finished': league.find('./yh:is_finished', self._ns) is not None } for league in tree.findall(".//yh:league", self._ns)] return [ League.update_or_create(_id=league['id'], key=league['key'], defaults=league)[0] for league in league_data ]
def get_league_resource(self, league_key, resource): return self._make_req('league/%s/%s' % (league_key, resource)) def get_team_resource(self, team_key, resource): return self._make_req('team/%s/%s' % (team_key, resource)) if __name__ == "__main__": api = API() api.auth() logger.info("Fetching leagues...") for league_id in USER_LEAGUE_IDS: League.delete().where(League.id == league_id) for league_key in PUBLIC_LEAGUE_KEYS: League.delete().where(League.key == league_key) leagues = api.get_user_leagues() leagues = list(filter(lambda l: int(l._id) in USER_LEAGUE_IDS, leagues)) leagues += [api.get_league(key) for key in PUBLIC_LEAGUE_KEYS] league_infos = [] for league in leagues: logger.info("Fetching teams for league %s (%s)...", league.name, league.season) league_info = {"name": league.name, "key": league.key} teams = api.get_league_teams(league)
def get(self): leagues = League.get_leagues() template = JINJA_ENVIRONMENT.get_template('index.html') self.response.write(template.render({"leagues": leagues}))
def get(self): league = League.new_league(self.request.get("name")) self.response.write("Created league %s" % league.name)
Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() newUser1 = User(name="Gary Bettman", email="*****@*****.**", picture="") session.add(newUser1) session.commit() newUser2 = User(name="Adam Silver", email="*****@*****.**", picture="") session.add(newUser1) session.commit() # NHL nhl = League(name="NHL", user=newUser1) session.add(nhl) session.commit() leafs = Team(name="Toronto Maple Leafs", league=nhl) session.add(leafs) session.commit() habs = Team(name="Montreal Canadiens", league=nhl) session.add(habs) session.commit() pens = Team(name="Pittsburgh Penguins", league=nhl) session.add(pens) session.commit()
# Add models in the DB Team.__table__.create(engine) League.__table__.create(engine) Game.__table__.create(engine) # LEAGUES # Fill leagues broker = 'med' leagues = config_results.BROKERS_LEAGUES[broker] # available_leagues available_leagues = [] for key, item in enumerate(leagues): country, level = item.split('_') name = leagues[item]['division'] league = League(name=name, country=country, level=level) session.add(league) session.commit() # --- # TEAM # Fill teams available_leagues = session.query(League).all() for league in available_leagues: country = league.country level = league.level league_file = f'../../data/results/leagues/league_{country}_{level}_{broker}.csv' teams = pd.read_csv(league_file) query = session.query(League).filter_by(country=country, level=level).all()[0]
def edit_game(request, game_id): game = Game.objects.get(id=game_id) league_list = League.objects.all() member_list = Member.objects.all() batting_query = Batting.objects.filter(game=game) pitching_query = Pitching.objects.filter(game=game) if request.method != "POST": game.date = unicode(game.date) away_name = game.away_name.encode('utf8') home_name = game.home_name.encode('utf8') game.away_scores = CommaSeparatedString_to_IntegerArray( game.away_scores) game.home_scores = CommaSeparatedString_to_IntegerArray( game.home_scores) message = "" warning = "" record_table = text_to_table(game.record.encode('utf8')) if (away_name.upper() == 'RB'): away_table = record_table home_table = [] else: away_table = [] home_table = record_table game_record, warning = parse_game_record(away_name, game.away_scores, away_table, \ home_name, game.home_scores, home_table) if (away_name.upper() == 'RB'): team = game_record.away else: team = game_record.home batting_list = [] for batting in batting_query: batting_list.append(batting) pitching_list = [] for pitching in pitching_query: pitching_list.append(pitching) # add rows for changing pitchers N = len(pitching_list) for i in range(5 - N): pitching_list.append(Pitching()) context = { 'league_list': league_list, 'game': game, 'warning': warning, 'message': message, 'game_record': game_record, 'team': team, 'member_list': member_list, 'batting_list': batting_list, 'pitching_list': pitching_list } return render(request, 'team/edit_game.html', context) else: # POST league_id = request.POST["league_id"] game.league = League.objects.get(id=league_id) game.date = request.POST["date"] game.location = request.POST["location"] game.record = request.POST["record_text"] game.away_name = request.POST["away_name"] game.home_name = request.POST["home_name"] game.away_scores = gather_team_scores_from_web(request, 'away') game.home_scores = gather_team_scores_from_web(request, 'home') print game.home_scores message = "" warning = "" game_record = None team = None if 'add-new-league-btn' in request.POST: print("add new league!") league_name = request.POST["new-league-name"] if league_name != None: league = League.objects.filter(name=league_name) if (league.exists()): warning = "League name %s already exists." % league_name else: league = League(name=league_name) league.save() message = 'Add new league: %s' % league_name league_list = League.objects.all() if 'add-new-member-btn' in request.POST: print("add new member!") member_name = request.POST["new-member-name"] member_number = int(request.POST["new-member-number"]) if member_name != None: member = Member.objects.filter(name=member_name) if (member.exists()): warning = "Member %s already exists." % member_name else: member = Member(name=member_name, number=member_number) member.save() message = 'Add new member: %s(%d)' % (member_name, member_number) member_list = Member.objects.all() if ('preview-btn' in request.POST) or ('save-game-btn' in request.POST): game.league = League.objects.get(id=league_id) record_table = text_to_table(game.record.encode('utf8')) away_name = game.away_name.encode('utf8') home_name = game.home_name.encode('utf8') if (away_name.upper() == 'RB'): away_table = record_table home_table = [] else: away_table = [] home_table = record_table game_record, warning = parse_game_record(away_name, game.away_scores, away_table, \ home_name, game.home_scores, home_table) game.away_R = game_record.away.R game.away_H = game_record.away.H game.away_E = game_record.away.E game.home_R = game_record.home.R game.home_H = game_record.home.H game.home_E = game_record.home.E if (warning == ""): message = "Preview record table!" game_record, team = extract_single_team_data(game_record, 'RB') batting_list = [] for batter in team.batters: batting = Batting() for play in batting_query: if batter.name.decode('utf8') == play.member.name: batting = play break batting.member = Member.objects.get( name=batter.name.decode('utf8')) batting.game = game batting.order = batter.order batting.pa = batter.PA batting.single = batter.B1 batting.double = batter.B2 batting.triple = batter.B3 batting.hr = batter.HR batting.rbi = batter.RBI batting.run = batter.RUN batting.bb = batter.BB batting.k = batter.K batting.sf = batter.SF batting.field = batter.pos batting_list.append(batting) # DO NOT modify pitching query with team.pitchers pitching_list = [] for pitching in pitching_query: pitching_list.append(pitching) # add rows for changing pitchers N = len(pitching_list) for i in range(5 - N): pitching_list.append(Pitching()) if 'save-game-btn' in request.POST: # create and save new Game object game.away_scores = IntegerArray_to_CommaSeparatedString( game.away_scores) game.home_scores = IntegerArray_to_CommaSeparatedString( game.home_scores) game.save() nBatter = len(batting_list) for i in range(nBatter): batting = batting_list[i] member_id = int( request.POST.get("batting_%d_id" % (i + 1), "")) if (member_id != 0): batting.member = Member.objects.get(id=member_id) batting.game = game batting.save() nPitcher = len(pitching_list) for i in range(nPitcher): pitching = pitching_list[i] member_id = int( request.POST.get("pitching_%d_id" % (i + 1), "")) if (member_id != 0): pitching.member = Member.objects.get(id=member_id) pitching.game = game pitching.outs = int( request.POST.get("pitching_%d_outs" % (i + 1), "")) pitching.pa = int( request.POST.get("pitching_%d_pa" % (i + 1), "")) pitching.hit = int( request.POST.get("pitching_%d_hit" % (i + 1), "")) pitching.hr = int( request.POST.get("pitching_%d_hr" % (i + 1), "")) pitching.bb = int( request.POST.get("pitching_%d_bb" % (i + 1), "")) pitching.k = int( request.POST.get("pitching_%d_k" % (i + 1), "")) pitching.run = int( request.POST.get("pitching_%d_run" % (i + 1), "")) pitching.er = int( request.POST.get("pitching_%d_er" % (i + 1), "")) pitching.go = int( request.POST.get("pitching_%d_go" % (i + 1), "")) pitching.fo = int( request.POST.get("pitching_%d_fo" % (i + 1), "")) win = request.POST.get("pitching_%d_win" % (i + 1), "") lose = request.POST.get( "pitching_%d_lose" % (i + 1), "") if (win != ''): pitching.win = 1 else: pitching.win = 0 if (lose != ''): pitching.lose = 1 else: pitching.lose = 0 pitching.save() return redirect("/game/" + str(game.id)) context = { 'league_list': league_list, 'game': game, 'warning': warning, 'message': message, 'game_record': game_record, 'team': team, 'member_list': member_list, 'batting_list': batting_list, 'pitching_list': pitching_list } return render(request, 'team/edit_game.html', context)
def add_or_edit_league(request, league=None): existing = "" if league: league = League.objects.get(pk=league) if request.method == "POST": if league: form = LeagueForm(request.POST) else: form = NewLeagueForm(request.POST) if form.is_valid(): if form.cleaned_data['join_leagues']: for league in form.cleaned_data['join_leagues']: # apply to join these leagues application = LeagueJoinStates.joined\ .apply_to_league(league, request.user) url = reverse('logged_in') return redirect(url) else: could_join = Set([]) applied = Set([]) invited = Set([]) # first, build three lists (applied, invited, # could_join) of leagues that people we're inviting # are already in for row in form.members.cleaned_data: if row: try: member = CustomUser.objects.get(email=row['email']) except CustomUser.DoesNotExist: continue user = request.user leagues = member.leagues_by_state(STATE_ACCEPTED) # don't include leagues we've already decided # not to join (or have been rejected from) leagues = leagues.exclude( leaguejoinstates__state=STATE_REJECTED, #leaguejoinstates__state=STATE_DECLINED, leaguejoinstates__user=user) if leagues: applied.update( leagues.filter( leaguejoinstates__state=STATE_APPLIED, leaguejoinstates__user=user)) invited.update( leagues.filter( leaguejoinstates__state=STATE_INVITED, leaguejoinstates__user=user)) could_join.update( leagues.exclude(leaguejoinstates__user=user)) if not request.POST.get('yes_really', '')\ and (could_join or applied or invited): # present the user with a choice to join other # leagues instead of making a new one # # XXX this is horrendous but I don't know how to # do it better choices = [(x.id, x.name) for x in could_join] form.fields['join_leagues'].choices = choices return locals() else: # create a new league and invite people to join it if not league: league = League(name=form.cleaned_data['name'], owner=request.user) league.save() # the current user will be a member, of course application = LeagueJoinStates(league=league, user=request.user, state=STATE_ACCEPTED) application.save() for row in form.members.cleaned_data: if not row: continue email = row['email'] try: member = CustomUser.objects.get(email=email) except CustomUser.DoesNotExist: create_user = CustomUser.objects.create_user member = create_user(username=email, email=email) member.save() try: profile = RegistrationProfile.objects\ .filter(user=member).get() except RegistrationProfile.DoesNotExist: profile = RegistrationProfile.objects\ .create_profile(member, email=False) invite = LeagueJoinStates.joined\ .invite_user(league, member) url = reverse('logged_in') return redirect(url) else: if league: form = LeagueForm() else: form = NewLeagueForm() return locals()
def add_game(request): league_list = League.objects.all() member_list = Member.objects.all() game = Game() batting_list = [] pitching_list = [] if request.method != "POST": game.date = None game.location = "" game.away_name = "" game.away_scores = [0] * 7 game.home_name = "" game.home_scores = [0] * 7 game.record = "" message = "" warning = "" context = { 'league_list': league_list, 'game': game, 'warning': warning, 'message': message } return render(request, 'team/add_game.html', context) else: league_id = request.POST["league_id"] game.league = League.objects.get(id=league_id) game.date = request.POST["date"] game.location = request.POST["location"] game.record = request.POST["record_text"] game.away_name = request.POST["away_name"] game.home_name = request.POST["home_name"] game.away_scores = gather_team_scores_from_web(request, 'away') game.home_scores = gather_team_scores_from_web(request, 'home') message = "" warning = "" game_record = None team = None if 'add-new-league-btn' in request.POST: print("add new league!") league_name = request.POST["new-league-name"] if league_name != None and league_name != "": league = League.objects.filter(name=league_name) if (league.exists()): warning = "League name %s already exists." % league_name else: league = League(name=league_name) league.save() message = 'Add new league: %s' % league_name league_list = League.objects.all() if 'add-new-member-btn' in request.POST: print("add new member!") member_name = request.POST["new-member-name"] member_number = int(request.POST["new-member-number"]) if member_name != None: member = Member.objects.filter(name=member_name) if (member.exists()): warning = "Member %s already exists." % member_name else: member = Member(name=member_name, number=member_number) member.save() message = 'Add new member: %s(%d)' % (member_name, member_number) member_list = Member.objects.all() if ('preview-btn' in request.POST) or ('save-game-btn' in request.POST): game.league = League.objects.get(id=league_id) record_table = text_to_table(game.record.encode('utf8')) away_name = game.away_name.encode('utf8') home_name = game.home_name.encode('utf8') if (away_name.upper() == 'RB'): away_table = record_table home_table = [] else: away_table = [] home_table = record_table game_record, warning = parse_game_record(away_name, game.away_scores, away_table, \ home_name, game.home_scores, home_table) game.away_R = game_record.away.R game.away_H = game_record.away.H game.away_E = game_record.away.E game.home_R = game_record.home.R game.home_H = game_record.home.H game.home_E = game_record.home.E if (warning == ""): message = "Preview record table!" game_record, team = extract_single_team_data(game_record, 'RB') # create and save new Batting object nBatter = len(team.batters) batting_list = [] for i in range(nBatter): batting = Batting() batting.game = game batting.order = team.batters[i].order batting.pa = team.batters[i].PA batting.single = team.batters[i].B1 batting.double = team.batters[i].B2 batting.triple = team.batters[i].B3 batting.hr = team.batters[i].HR batting.rbi = team.batters[i].RBI batting.run = team.batters[i].RUN batting.bb = team.batters[i].BB batting.k = team.batters[i].K batting.sf = team.batters[i].SF batting.field = team.batters[i].pos try: batting.member = Member.objects.get( name=team.batters[i].name.decode('utf8')) except Member.DoesNotExist: warning = "member name %s does not exist." % team.batters[ i].name break batting_list.append(batting) # create and save new Batting object nPitcher = len(team.pitchers) pitching_list = [] for i in range(nPitcher): pitching = Pitching() pitching.game = game pitching.order = i pitching.outs = team.pitchers[i].OUT pitching.pa = team.pitchers[i].TBF pitching.hit = team.pitchers[i].H pitching.hr = team.pitchers[i].HR pitching.bb = team.pitchers[i].BB pitching.k = team.pitchers[i].K pitching.run = team.pitchers[i].RUN pitching.er = team.pitchers[i].ER pitching.go = team.pitchers[i].GO pitching.fo = team.pitchers[i].FO pitching.win = team.pitchers[i].WIN pitching.lose = team.pitchers[i].LOSE try: pitching.member = Member.objects.get( name=team.pitchers[i].name.decode('utf8')) except Member.DoesNotExist: warning = "member name %s does not exist." % team.pitchers[ i].name break pitching_list.append(pitching) # add rows for changing pitchers N = len(pitching_list) for i in range(5 - N): pitching_list.append(Pitching()) if 'save-game-btn' in request.POST: # create and save new Game object game.away_scores = IntegerArray_to_CommaSeparatedString( game.away_scores) game.home_scores = IntegerArray_to_CommaSeparatedString( game.home_scores) game.save() nBatter = len(batting_list) for i in range(nBatter): batting = batting_list[i] member_id = int( request.POST.get("batting_%d_id" % (i + 1), "")) if (member_id != 0): batting.member = Member.objects.get(id=member_id) batting.game = game batting.save() nPitcher = len(pitching_list) for i in range(nPitcher): pitching = pitching_list[i] member_id = int( request.POST.get("pitching_%d_id" % (i + 1), "")) if (member_id != 0): pitching.member = Member.objects.get(id=member_id) pitching.game = game pitching.outs = int( request.POST.get("pitching_%d_outs" % (i + 1), "")) pitching.pa = int( request.POST.get("pitching_%d_pa" % (i + 1), "")) pitching.hit = int( request.POST.get("pitching_%d_hit" % (i + 1), "")) pitching.hr = int( request.POST.get("pitching_%d_hr" % (i + 1), "")) pitching.bb = int( request.POST.get("pitching_%d_bb" % (i + 1), "")) pitching.k = int( request.POST.get("pitching_%d_k" % (i + 1), "")) pitching.run = int( request.POST.get("pitching_%d_run" % (i + 1), "")) pitching.er = int( request.POST.get("pitching_%d_er" % (i + 1), "")) pitching.go = int( request.POST.get("pitching_%d_go" % (i + 1), "")) pitching.fo = int( request.POST.get("pitching_%d_fo" % (i + 1), "")) win = request.POST.get("pitching_%d_win" % (i + 1), "") lose = request.POST.get( "pitching_%d_lose" % (i + 1), "") if (win != ''): pitching.win = 1 else: pitching.win = 0 if (lose != ''): pitching.lose = 1 else: pitching.lose = 0 pitching.save() return redirect("/game/" + str(game.id)) # end of add-game-btn # end of preview context = { 'league_list': league_list, 'game': game, 'warning': warning, 'message': message, 'game_record': game_record, 'team': team, 'member_list': member_list, 'batting_list': batting_list, 'pitching_list': pitching_list } return render(request, 'team/add_game.html', context)