def activate_study(request, code): try: cron = Cron.objects.get(activationCode=code) except Cron.DoesNotExist: cron = None if cron == None: return render(request, 'players/registration.html', {"wrongCode": True}) elif cron.activated: return render(request, 'players/registration.html', {"alreadyActivated": True}) else: if request.method == 'POST': form = PlayerForm(request.POST, prefix="player") if form.is_valid(): player = form.save() cron.player = player cron.activated = True cron.save() logging.log_action(ActionLog.ACTION_CRON_ACTIVATED, cron) return render(request, 'players/registration.html', {"cron": player.cron, "study":True}) else: return render(request, 'players/study.html', {"form": form, "code":code}) else: form = PlayerForm(prefix='player') logging.log_action(ActionLog.ACTION_CRON_VIEW_STUDY, cron) return render(request, 'players/study.html', {"form": form, "code":code})
def register(request): uform = UserForm(request.POST or None) form = PlayerForm(request.POST or None) if uform.is_valid() and form.is_valid(): dj_user = uform.save() player = form.save(commit=False) player.user = dj_user prof = Profile() prof.save() player.profile = prof player.save() #authenticate user #dj_user = authenticate(username=uform.cleaned_data['username'], # password=uform.cleaned_data['password'], # ) #login(request, dj_user) #success sends to map and the questions.. return redirect(reverse('login')) #register invalid.. go back to register (test registration errors!! probably fix css for errors) return render(request, 'registration/register.html', context={ 'form': form, 'uform': uform })
def player_view(game_name,player_name): """Player Page""" #make SQL request game_archive = GameArchive.query.filter_by(game_name=game_name) #rebuild class instance game = unpack_game(game_archive) #make submit form player_form = PlayerForm() #make swap letter form swap_form = SwapLettersForm() #validation for play submission if player_form.validate_on_submit(): #parse tile positions tile_pos = [(int(r),int(c)) for r,c in zip(player_form.rows.data.split(','), player_form.cols.data.split(','))] #play word played_word = game.players[player_name].play_word(word=player_form.word_play.data, tile_pos=tile_pos) #place tiles game.board.place_tiles(played_word) #draw letters game.tilebag.draw_letters(game.players[player_name]) #update database update_game(game,game_archive) elif swap_form.validate_on_submit(): #swap_letter game.tilebag.swap_letter(game.players[player_name],swap_form.letter.data) #update database update_game(game,game_archive) return render_template('player.html', submit_form=player_form, swap_form=swap_form, letter_rack=game.players[player_name].letter_rack, num_letters=len(game.players[player_name].letter_rack), name=player_name, square=2*s)
def put(self, request): player = Player() data = json.loads(request.body) if data.get("project"): data["project"] = AdviserProject.objects.get(id=data["project"]) player_form = PlayerForm(data) if not player_form.is_valid(): return HttpResponseBadRequest("Invalid input data. Please edit and try again.") player.set(data) return HttpResponse(status=201)
def post(self, request, *args, **kwargs): form = PlayerForm(request.POST) if form.is_valid(): player, created = Player.objects.get_or_create(username=request.POST.get('username'), password=request.POST.get('password'), elo=request.POST.get('elo')) game = get_object_or_404(Game, slug=kwargs['slug_game']) game.players.add(player) Result.objects.get_or_create(player=player, game=game) return HttpResponseRedirect(reverse('players-list', args={kwargs['slug_game']}))
def new_player(request): if request.method == 'POST': pf = PlayerForm(request.POST) if pf.is_valid(): new_p = pf.save(commit=False) new_p.balance = STARTING_BALANCE new_p.save() return redirect('bank.views.player', new_p.id) else: pf = PlayerForm() return render(request, "new_player.html", {'form': pf})
def create(request): if request.POST: form = PlayerForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/players/') else: form = PlayerForm() args = {} args.update(csrf(request)) args['form'] = form return render_to_response('players/create.html', args)
def player_view(game_name, player_name): """Player Page""" #rebuild class instance from SQL request game_archive = GameArchive.query.filter_by(game_name=game_name) game = Game.unarchive(game_archive) #make forms player_form = PlayerForm() swap_form = SwapLettersForm() #validation for play submission if player_name != game.player_order[0]: pass elif player_form.validate_on_submit(): #parse tile positions tile_pos = [(int(r), int(c)) for r, c in zip(player_form.rows.data.split(','), player_form.cols.data.split(','))] #play word played_word = game.players[player_name].play_word( word=player_form.word_play.data, tile_pos=tile_pos) #place tiles coords = game.board.place_tiles(played_word) #score word game.score_word(coords, player_name) #draw letters game.tilebag.draw_letters(game.players[player_name]) #increment turn list game.player_order.append(game.player_order.pop(0)) #update database game.archive(db, archive=game_archive) elif swap_form.validate_on_submit(): #swap_letter game.tilebag.swap_letter(game.players[player_name], swap_form.letter.data) #increment turn list game.player_order.append(game.player_order.pop(0)) #update database game.archive(db, archive=game_archive) #first render the JS d3_rack = render_template( 'js/player.js', square=2 * s, letter_rack=game.players[player_name].letter_rack, num_letters=len(game.players[player_name].letter_rack)) return render_template('player.html', submit_form=player_form, swap_form=swap_form, name=player_name, your_turn=player_name == game.player_order[0], d3_rack=d3_rack)
def register(request): if request.method == 'POST': player_form = PlayerForm(request.POST, prefix="player") user_form = UserCreationForm(request.POST, prefix = "user") passcode = request.POST.get('registration_passcode', '') if passcode == registration_passcode and player_form.is_valid() and user_form.is_valid(): player = player_form.save() user = user_form.save() cron = Cron() cron.player = player cron.user = user cron.activated = False cron.save() provlog_add_cron_register(cron) email_tpl = loader.get_template('players/activation.txt') url = request.build_absolute_uri(reverse('players_activation', args=[cron.activationCode])) c = Context({ 'cron': cron, 'url':url }) email = EmailMessage( subject='[cr0n] Activate your account', body= email_tpl.render(c), to=[cron.player.email,], ) #in settings.py you can configure console backend for displaying emails instead of sending them - great for testing! email.send(fail_silently=True) return render_to_response('players/registration.html', {"registered": True, "cron":cron}) else: return render_to_response( 'players/registration.html', {"player_form": player_form, "user_form": user_form}, context_instance=RequestContext(request) ) else: player_form = PlayerForm(prefix='player') user_form = UserCreationForm(prefix='user') return render_to_response( 'players/registration.html', {"player_form": player_form, "user_form": user_form}, context_instance=RequestContext(request) )
def edit(request, player_id): if player_id: player = Player.objects.get(id=player_id) if request.method == "POST": form = PlayerForm(request.POST, instance=player) if form.is_valid(): form.save() return HttpResponseRedirect('/players/') else: form = PlayerForm(instance=player) args = {} args.update(csrf(request)) args['form'] = form args['player'] = player return render_to_response('players/edit.html', args)
def addplayerinfo(request, idplayer, idtournament): if request.user.is_anonymous(): return HttpResponseRedirect('/login') try: usuario = UserProfile.objects.get(user=request.user) except Exception: usuario = None if usuario.userType == 'PR': try: publish_one = Publicity.objects.all().order_by('?').first() except Exception: publish_one = False try: publish_second = Publicity.objects.all().exclude(id=publish_one.id).order_by('?').first() except Exception: publish_second = False if request.POST: mform = PlayerForm(request.POST) if mform.is_valid(): #if the information in the form its correct #First, save the default User model provided by Django player = PlayersInfo( goals=mform.cleaned_data['goals'], yellowCards=mform.cleaned_data['yellowCards'], redCards=mform.cleaned_data['redCards'], user=UserProfile.objects.get(user_id=idplayer), tournament= Tournament.objects.get(id=idtournament), ) if usuario.userType == 'PR' and usuario.user == player.tournament.complex.user: player.save() return HttpResponseRedirect('/playersinfo') else: torneo = Tournament.objects.get(id=idtournament) if torneo.complex.user!=request.user: raise Http404 else: mform = PlayerForm() player_id = UserProfile.objects.get(id=idplayer) return render_to_response('playersinfo/addplayerinfo.html', {'mform': mform, 'player_id':player_id,'idtournament':idtournament,'publish_one':publish_one,'publish_second':publish_second}, RequestContext(request, {})) else: message = """ Oops!!! ha ocurrido un inconveniente, no tienes los permisos necesarios para crear estadisticas. Si el inconveniente persiste contactese. """ sendmail = True return render_to_response('404.html',{'message':message,'sendmail':sendmail})
def run_add_cast(request, run_id): """ FIXME @param request: @type request: @param run_id: @type run_id: """ run = get_object_or_404(Run, pk=run_id) aPlayer = Player(run=run, user=request.user) if request.method == "POST": form = PlayerForm(request.POST, instance=aPlayer) if form.is_valid(): if request.POST['character']: aChar=get_object_or_404(Character, pk=request.POST['character']) else: if request.POST["characterName"]!="": aChar=Character(larp=run.larp, name=request.POST["characterName"]) aChar.save() else: aChar=False if aChar: aPlayer=Player(run=run, user=request.user, character=aChar, characterName=request.POST['characterName']) aPlayer.save() else: aPlayer=Player(run=run, user=request.user) aPlayer.save() return HttpResponseRedirect(run.get_absolute_url()) else: form = PlayerForm() form.run=run_id if run.is_past: form.fields["character"].queryset = Character.objects.filter(larp=run.larp) else: if run.larp.spoilerability == 'ch': form.fields["character"].queryset = Character.objects.none() else: form.fields["character"].queryset = Character.objects.filter(larp=run.larp, spoiler=False) return render_to_response('eventCRUD/cast_add.html', { 'form':form, 'run':run, }, context_instance=RequestContext(request) )
def player_view(game_name,player_name): """Player Page""" #rebuild class instance from SQL request game_archive = GameArchive.query.filter_by(game_name=game_name) game = Game.unarchive(game_archive) #make forms player_form = PlayerForm() swap_form = SwapLettersForm() #validation for play submission if player_name != game.player_order[0]: pass elif player_form.validate_on_submit(): #parse tile positions tile_pos = [(int(r),int(c)) for r,c in zip(player_form.rows.data.split(','), player_form.cols.data.split(','))] #play word played_word = game.players[player_name].play_word(word=player_form.word_play.data, tile_pos=tile_pos) #place tiles coords = game.board.place_tiles(played_word) #score word game.score_word(coords,player_name) #draw letters game.tilebag.draw_letters(game.players[player_name]) #increment turn list game.player_order.append(game.player_order.pop(0)) #update database game.archive(db,archive=game_archive) elif swap_form.validate_on_submit(): #swap_letter game.tilebag.swap_letter(game.players[player_name],swap_form.letter.data) #increment turn list game.player_order.append(game.player_order.pop(0)) #update database game.archive(db,archive=game_archive) #first render the JS d3_rack = render_template('js/player.js',square=2*s, letter_rack=game.players[player_name].letter_rack, num_letters=len(game.players[player_name].letter_rack)) return render_template('player.html',submit_form=player_form,swap_form=swap_form, name=player_name,your_turn=player_name==game.player_order[0], d3_rack=d3_rack)
def new_player(request): if request.method == "POST": form = PlayerForm(request.POST) if form.is_valid(): player = form.save(commit=False) player.save() messages.success( request, "You have added " + player.name + " " + player.last_name + " to " + player.team.name + " Team!") return redirect('get_team', player.team_id) else: messages.error(request, 'Please correct the errors below.') else: form = PlayerForm() if request.user.is_superuser: form.fields['team'].queryset = Team.objects.all() else: form.fields["team"].queryset = Team.objects.filter( id=request.user.profile.team_id) return render( request, 'form.html', { 'form': form, 'heading_text': 'You are creating a new player!', 'button_text': 'Save Player', })
def edit_player(request, id): player = get_object_or_404(Player, pk=id) if request.method == "POST": form = PlayerForm(request.POST, request.FILES, instance=player) if form.is_valid(): player = form.save(False) player.save() messages.success( request, "You have edited " + player.name + ' ' + player.last_name + "!") return redirect('get_team', player.team_id) else: messages.error(request, 'Please correct the errors below.') else: form = PlayerForm(instance=player) if request.user.is_superuser: form.fields['team'].queryset = Team.objects.all() else: form.fields['team'].queryset = Team.objects.filter( id=request.user.profile.team_id) | Team.objects.filter( name="Unassigned") return render( request, 'form.html', { 'form': form, 'cancelview': "get_team", 'cancelid': player.team.id, 'heading_text': 'You are editing ' + player.name + ' ' + player.last_name, 'button_text': 'Save Player', })
def player_view(game_name, player_name): """Player Page""" #make SQL request game_archive = GameArchive.query.filter_by(game_name=game_name) #rebuild class instance game = unpack_game(game_archive) #make submit form player_form = PlayerForm() #make swap letter form swap_form = SwapLettersForm() #validation for play submission if player_form.validate_on_submit(): #parse tile positions tile_pos = [(int(r), int(c)) for r, c in zip(player_form.rows.data.split(','), player_form.cols.data.split(','))] #play word played_word = game.players[player_name].play_word( word=player_form.word_play.data, tile_pos=tile_pos) #place tiles game.board.place_tiles(played_word) #draw letters game.tilebag.draw_letters(game.players[player_name]) #update database update_game(game, game_archive) elif swap_form.validate_on_submit(): #swap_letter game.tilebag.swap_letter(game.players[player_name], swap_form.letter.data) #update database update_game(game, game_archive) return render_template('player.html', submit_form=player_form, swap_form=swap_form, letter_rack=game.players[player_name].letter_rack, num_letters=len( game.players[player_name].letter_rack), name=player_name, square=2 * s)
def arena(request,username, name): t=StudentTeam.objects.get(pk=name) next_month=month.objects.get(month_id=t.cm.month_id+1) if not next_month: t.game_stop=True if t.game_stop: return HttpResponseRedirect(BASE_URL+'%(username)s/%(name)s/game/expiry/0/' %{"username":username,"name":name}) p=ParameterSet.objects.get(pk=1) month0tm=TeamMonth.objects.filter(team=t).filter(month=t.cm)[0] warning=check_for_wc(t,month0tm) if request.method=='POST': form=PlayerForm(request.POST) if form.is_valid(): s=form.cleaned_data['strat_num'] if(s<=t.mns): if not form.cleaned_data['systems']: form.cleaned_data['systems']=0 if not form.cleaned_data['research']: form.cleaned_data['research']=0 if not form.cleaned_data['marketing']: form.cleaned_data['marketing']=0 record_new_month(t,p,s,form.cleaned_data['systems'],form.cleaned_data['research'],form.cleaned_data['marketing'],month0tm) return HttpResponseRedirect(BASE_URL+'%(username)s/%(name)s/game/3/' %{"username":username,"name":name}) else: month0tm=rounding(month0tm) return render_to_response('game/Step1.html', {'name': name, 'username': username, 'status':t.approve,'prev_month':month0tm, 'month':next_month, 'form':form, 'error':'You cannot trade more than %s strategies'%(t.mns),'warning':warning, 'limit':t.round_limit, 'lmonth':t.round_limit.strftime("%B")},RequestContext(request)) else: month0tm=rounding(month0tm) return render_to_response('game/Step1.html', {'name': name, 'username': username, 'status':t.approve,'prev_month':month0tm,'warning':warning, 'month':next_month, 'form':form, 'error':'Invalid', 'limit':t.round_limit, 'lmonth':t.round_limit.strftime("%B")},RequestContext(request)) else: month0tm=rounding(month0tm) t.round_limit= datetime.datetime.now() + timedelta(minutes=p.round_limit) t.save() form=PlayerForm() if(t.cm.month_id==t.launch_month.month_id-1): wc=month0tm.wc+month0tm.aum rc=(p.variable_rc*t.saum/12)+p.fixed_rc return render_to_response('game/Step1_launch.html', {'name': name, 'username': username, 'status':t.approve, 'wc':wc,'rc':rc, 'month':next_month, 'form':form, 'error':False, 'limit':t.round_limit,'warning':warning, 'lmonth':t.round_limit.strftime("%B")},RequestContext(request)) return render_to_response('game/Step1.html', {'name': name, 'username': username, 'status':t.approve,'prev_month':month0tm, 'month':next_month, 'form':form, 'error':False, 'limit':t.round_limit,'warning':warning, 'lmonth':t.round_limit.strftime("%B")},RequestContext(request))
def profile(request): try: profile = request.user.get_profile() except player.DoesNotExist: profile = player(user=request.user) saved = None if request.method == "POST": form = PlayerForm(request.POST) if form.is_valid(): request.user.first_name = form.cleaned_data["first_name"] request.user.last_name = form.cleaned_data["last_name"] request.user.email = form.cleaned_data["email"] profile.gender = form.cleaned_data["gender"] profile.date_of_birth = form.cleaned_data["date_of_birth"] profile.countryPart = form.cleaned_data["countryPart"] profile.city = form.cleaned_data["city"] profile.street = form.cleaned_data["street"] profile.email = form.cleaned_data["email"] profile.phone = form.cleaned_data["phone"] profile.about_me = form.cleaned_data["about_me"] request.user.save() profile.save() saved = True return render_to_response( "players/profile.html", {"form": form, "saved": saved}, context_instance=RequestContext(request) ) else: return render_to_response( "players/profile.html", {"form": form, "fail": True}, context_instance=RequestContext(request) ) else: form = PlayerForm( initial={ "username": request.user.username, "first_name": request.user.first_name, "last_name": request.user.last_name, "city": profile.city, "street": profile.street, "email": request.user.email, "phone": profile.phone, "gender": profile.gender, "date_of_birth": profile.date_of_birth, "about_me": profile.about_me, "countryPart": profile.countryPart, } ) return render_to_response("players/profile.html", {"form": form}, context_instance=RequestContext(request))