def register(request): basic = get_basic(request) if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password1'] email = request.POST['email'] user = User.objects.create_user(username, email, password) user.is_active = False user.save() characters = string.ascii_uppercase + string.digits + string.ascii_lowercase confirmation_code = ''.join(random.choice(characters) for x in range(30)) register = Registration(user=user, confirmation_code=confirmation_code) register.save() user = authenticate(username=username, password=password) if user.is_active: login(request, user) return HttpResponseRedirect('/editprofile/') else: send_registration_confirmation(user) return HttpResponseRedirect('/accounts/notverified?id=' + str(user.id)) else: if basic: return HttpResponseRedirect('/') form = RegisterForm() return render(request, 'register.html', {'form': form, 'basic': basic})
def add_phone(request, phone): '''Adds a new phone to our list of users and sends a verification SMS. Args: phone: mobile phone number in the format - 00 area_code phone_number eg. 0061424387059 Returns: JSON status, either 'ok' or 'fail'. Raises: None ''' if request.method == 'GET': registration = Registration() registration.phone = phone registration.pin = generate_pin(4)[0] registration.save() if sendsms(phone, registration.pin): return HttpResponse(json.dumps('ok'), mimetype='application/json') else: return HttpResponse(json.dumps('fail'), mimetype='application/json') else: return HttpResponse(json.dumps('fail'), mimetype='application/json')
def save(self): data = self.cleaned_data user = data['user'] competition = data['competition'] r = Registration(user=user, competition=competition) r.save() return r
def charge(): def str2date(date_string): """ Returns a datetime date given a valid date_string """ return datetime.datetime.strptime(date_string, "%Y-%m-%d").date() if request.method == 'POST': try: # Amount in pence customer = stripe.Customer.create( email=request.form['stripeEmail'], card=request.form['stripeToken'] ) charge = stripe.Charge.create( customer=customer.id, amount=Decimal(session['registration_price']), currency='gbp', description='Registration' ) sob_date = None if session['sobriety_date'] != u'None': sob_date = str2date(session['sobriety_date']) registration = Registration( first_name = session['first_name'] , last_name = session['last_name'] , mobile = session['mobile'] , email = session['email'] , sobriety_date = sob_date , ypaa_committee = session['ypaa_committee'] , fellowship = session['fellowship'] , special_needs = session['special_needs'] , of_service = session['of_service'] , country = session['country'] ) registration.put() email_admin(session) email_user(session) flash("You are now registered!") if sob_date is not None: num_twins = num_sobriety_twins(str2date(session['sobriety_date'])) if num_twins > 1: if num_twins == 2: flash("By the way, you have a sobriety twin coming to the convention!") else: flash("By the way, you have %d sobriety twins coming to the convention!" % (num_twins-1)) return redirect(url_for('homepage')) except Exception, e: # TODO: Roll back transaction, registration #print "Payment not processed: %s" % e flash("Payment not processed. %s" % e) return redirect(url_for('new_registration_1'))
def make_test_registrations(): raid = Raid.objects.all()[0] raid.registered.clear() raid.has_rolled = False for player in User.objects.all(): registration = Registration(player=player, raid=raid, standby=not random.randrange(10), role=['dps', 'tank', 'healer'][random.randrange(3)]) registration.save() raid.save()
def continue_scenario(self, text, state, user_id): steps = SCENARIOS[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context): # next step next_step = steps[step['next_step']] self.send_step(step=next_step, user_id=user_id, text=text, context=state.context) if next_step['next_step']: # switch to next step state.step_name = step['next_step'] else: # finish scenario self.bot_log.info( 'Зарегистрирован: {name} {email}'.format(**state.context)) Registration(name=state.context['name'], email=state.context['email']) state.delete() else: # retry current step text_to_send = step['failure_text'].format(**state.context) self.send_text(text_to_send=text_to_send, user_id=user_id)
def continue_scenario(self, text, state, user_id): steps = settings.SCENARIOS[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context, settings_dict=self.cities): # next step start_over = state.context.get('start_over') if start_over: self.send_text(text_to_send='К сожалению, нам придется завершить сценарий', user_id=user_id) state.delete() return next_step = steps[step['next_step']] self.send_step(next_step, user_id, text, state.context) if next_step['next_step']: # switch to next step state.step_name = step['next_step'] else: # finish scenario log.info( 'Билет из {dep_city}, в {dest_city}, на дату {flight}, {number_of_tickets} билетов, комментарий: {commentary}, телефон: {telephone}, имя: {fio}'.format( **state.context)) Registration(dep_city=state.context['dep_city'], dest_city=state.context['dest_city'], date=state.context['flight'], tickets=state.context['number_of_tickets'], commentary=state.context['commentary'], telephone=state.context['telephone']) state.delete() else: # retry current step print(state.context) text_to_send = step['failure_text'].format(**state.context) self.send_text(text_to_send, user_id)
def continue_scenario(self, text, state, user_id): steps = settings.SCENARIOS[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context): # next step next_step = steps[step['next_step']] self.send_step(next_step, user_id, text, state.context) if next_step['next_step']: # switch to next step state.step_name = step['next_step'] else: # finish scenario log.info('Куплен билет на номер {phone_number}'.format( **state.context)) Registration(phone_number=state.context['phone_number'], user_info=state.context['user_info']) state.delete() else: # retry current step if step['action'] is not None: action_func = getattr(actions, step['action']) text_to_send, kwargs = action_func(state.context) reset_scenario_flag = kwargs.get('reset_scenario', False) if reset_scenario_flag: state.delete() else: text_to_send = step['failure_text'].format(**state.context) self.send_text(text_to_send, user_id)
def finish_scenario(self, state): """ Завершение текущего сценария :param state: состояние текущей процедуры :type state: models.UserState :return: None """ if state.scenario_name == 'coffee': log.info('Выдан кофе') self.pay.get_empty_keyboard() state.delete() elif state.scenario_name == 'registration': log.info('Зарегистрирован: {name} {email}'.format(**state.context)) Registration(name=state.context['name'], email=state.context['email']) BonusCardCoffee(email_card=state.context['email'], count=0) state.delete() elif state.scenario_name == 'airplane': log.info('Зарегистрирован на полёт: {name} {connect}. Рейс: {landing}-{direction}, {date_reg}' .format(**state.context)) RegistrationAirline(name=state.context['name'], connect=state.context['connect'], landing=state.context['landing'], direction=state.context['direction'], date_reg=state.context['date_reg'], date_landing=state.context['date_landing'], date_direction=state.context["date_direction"]) state.delete() else: state.delete()
def continue_scenario(self, text, state, user_id): """Переход на следующий шаг сценария бота""" steps = settings.SCENARIOS[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context): next_step = steps[step['next_step']] self.send_step(next_step, user_id, text, state.context) if next_step['next_step']: state.step_name = step['next_step'] else: log.info( 'Зарегистрирован: {name} {city_from} - {city_to} {flight} {seats} seats "{comment}" {phone} {email}' .format(**state.context)) Registration( city_from=state.context['city_from'], city_to=state.context['city_to'], flight=state.context['flight'], seats=state.context['seats'], comment=state.context['comment'], name=state.context['name'], email=state.context['email'], phone=state.context['phone'], ) state.delete() else: if 'stop' in state.context: text_to_send = step['stop_scenario'].format(**state.context) self.send_text(text_to_send, user_id) state.delete() else: text_to_send = step['failure_text'].format(**state.context) self.send_text(text_to_send, user_id)
def check_phone_number(update, context): """ Проверка номера телефона пользователя и занесение данных в БД """ if update.message.text == "да": log.info(f"получен верный номер телефона") update.message.reply_text(f"Спасибо, {context.user_data['name']}! Ожидайте звонка. Ваш билет.") image_ticket = make_ticket( fio=context.user_data['name'], from_=context.user_data["city_of_departure"], to=context.user_data["arrival_city"], date=context.user_data["date_of_departure"], person=context.user_data["name_avatar"] ) context.bot.send_photo(chat_id=update.message.chat.id, photo=open(image_ticket, 'rb')) Registration( name=context.user_data['name'], date_of_departure=context.user_data["date_of_departure"], city_of_departure=context.user_data["city_of_departure"], arrival_city=context.user_data["arrival_city"], flight=context.user_data["flight"], number_of_seats=context.user_data["number_of_seats"], comment=context.user_data["comment"], phone_number=context.user_data["phone_number"], name_avatar=context.user_data["name_avatar"] ) return ConversationHandler.END else: log.info(f"получен неверный номер телефона") update.message.reply_text("Введите номер телефона.") return PHONE_NUMBER
def db_info(self, state, step, user_id, text): """ Манипуляция с базой данных :param state: Текущее контекст (хранит последнее действие от пользователя) :param step: текущий шаг :param user_id: id пользователя :param text: текст от пользователя :return: False, если в сценарии 'registration' найдено совпадения по зарегистрированному email; continue - в сценарии 'coffee' найден пользователь; True - нет подходящего сценария """ if state.scenario_name == 'registration': for i in Registration.select(): if text == i.email: text_to_send = step['failure_text2'].format(**state.context) self.send_text(text_to_send, user_id) return False elif state.scenario_name == 'coffee': res = BonusCardCoffee.select(lambda x: x.count < 10 and x.email_card == text) if res: for user in res: user.count += 1 self.send_text('Да, сегодня ещё есть бесплатный кофе', user_id) return 'continue' else: self.send_text(step['failure_text'], user_id) else: return True
def continue_scenario(self, text, state, user_id): steps = settings.SCENARIOS[state.scenario_name]["steps"] step = steps[state.step_name] handler = getattr(handlers, step["handler"]) if handler(text=text, context=state.context): # next step next_step = steps[step["next_step"]] self.send_step(next_step, user_id, text, state.context) if next_step["next_step"]: # switch to next step state.step_name = step["next_step"] else: # finish scenario log.info(state.context) Registration(departure=state.context['departure'], arrival=state.context['arrival'], chosen_date=state.context['chosen_date'], places=state.context['places'], phone_number=state.context['number'], email=state.context['email'], confirmed=state.context['confirmed'], comment=state.context['comment']) state.delete() else: # retry current step text_to_send = step["failure_text"].format(**state.context) self.send_text(text_to_send, user_id)
def continue_scenario(self, text, state, user_id): """Продолжить сценарий для пользователя. :param user_id: id пользователя :param text: сообщение пользователя :param state: состояние, в котором находится пользователь :param user_id: id пользователя :return: сообщение, которое необходимо отправить пользователю. """ steps = settings.SCENARIOS[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context): next_step = steps[step['next_step']] self.send_step(next_step, user_id, text, state.context) if next_step['next_step']: state.step_name = step['next_step'] else: log.info( 'Зарестрирован: {name} {email}'.format(**state.context)) Registration(name=state.context['name'], email=state.context['email']) state.delete() else: # повторить шаг текущего сценария text_to_send = step['failure_text'].format(**state.context) self.send_text(text_to_send, user_id)
def continue_scenario(self, text, state, user_id): steps = settings.SCENARIOS[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context, user_date=self.user_time): # next step next_step = steps[step['next_step']] self.send_step(next_step, user_id, text, state.context) if next_step['next_step']: # switch next step state.step_name = step['next_step'] else: # finish scenario state.delete() log.info('Город отправления - {departure_city}\n' 'Город назначения - {destination_city}\n' 'Дата отправления - {departure_date}\n' 'Выбранный рейс - {num_flight}\n' 'Количество мест - {num_seats}\n' 'Комментарий к заказу:\n' '{comment}\n'.format(**state.context)) Registration( name=self.name, departure_city=state.context['departure_city'], destination_city=state.context['destination_city'], departure_date=state.context['departure_date'], num_flight=state.context['num_flight'], num_seats=state.context['num_seats'], comment=state.context['comment'], phone_number=state.context['phone_number'], ) else: # retry current step text_to_send = step['failure_text'].format(**state.context) self.send_text(text_to_send, user_id)
def import_typeform(filename): import csv fields = ["id"] + typeform.FIELDS + [ "start_time", "submit_time", "network_id" ] vals = [] with open(filename, newline='') as csvfile: reader = csv.DictReader(csvfile, fields) for row in reader: row["first_hack"] = row["first_hack"] == "1" row["sponsor"] = row["sponsor"] == "1" row["swag"] = row["swag"] == "1" row["code_of_conduct"] = row["code_of_conduct"] == "1" row["terms_and_conditions"] = row["terms_and_conditions"] == "1" vals.append(row) create_tables() with db.database.atomic(): (Registration.insert_many(vals[1:]).on_conflict( "update", conflict_target=[Registration.id], preserve=Registration.hacker_discord).execute()) click.echo("Uploaded {0} entries to the Registration table".format( len(vals) - 1))
def continue_scenario(self, text, state, user_id): """ Continues user scenario :param text: parameter for handler :param state: current state :param user_id: vk user id :return: None """ steps = settings.SCENARIOS[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context): # next step next_step = steps[step['next_step']] self.send_step(next_step, user_id, text, state.context) if next_step['next_step']: # switch to next_step state.step_name = step['next_step'] else: # finish scenario log.info( 'Зарегистрирован: {name} {email}'.format(**state.context)) Registration(name=state.context['name'], email=state.context['email']) state.delete() else: # retry current step text_to_send = step['failure_text'].format(**state.context) self.send_text(text_to_send, user_id)
def input_grade(self, student_id, section_id, percent_grade, letter_grade): update = (Registration.update( percent_grade=percent_grade, letter_grade=letter_grade).where( Registration.student_id == student_id, Registration.section_id == section_id)) return update.execute()
def post(self, request, *args, **kwargs): email = request.POST.get("email", None) if email is not None: url = request.build_absolute_uri( reverse("signup", kwargs={"token": self.generate_signup_token(email)})) html = get_template("registration/email.html") content = html.render({"url": url}) msg = "Kindly visit %s to create an account" % url send_mail( "Computer Science & I.T Department Timetable Registration", msg, "*****@*****.**", [email], fail_silently=False, html_message=content, ) Registration(email=email).save() messages.success(request, "Registration email sent successfully", extra_tags="alert") return super().get(request) else: messages.warning(request, "An error occured while sending email") return render(request, self.template_name, {})
def get_student_terms(self): student_id = self.get_payload()['id'] query = (Registration.select(Term.title, Term.id).distinct().join( Section, on=(Registration.section_id == Section.id)).join( Term, on=(Section.term_id == Term.id)).where( Registration.student_id == student_id).dicts()) return query
def get_section_roster(self): section_id = self.get_payload()['section_id'] query = (Registration.select( Student.first_name, Student.last_name, Student.id, Registration.letter_grade, Registration.percent_grade).join(Student).where( Registration.section_id == section_id).dicts()) return query
def register(request, slug): e = Event.objects.get(slug=slug) u = request.user # if there are no non-cancelled registrations for this user/event and # registration is possible if (is_registered(u, e) == False and is_waitlisted(u, e) == False and e.is_registration_open() == True): # Since the event object will become aware of this registration # as soon as it saves, we need to cache the value. This might bite us? # # Check it: # # There's a class with a size of one with waitlist enabled. If # we save now the check to send the email will happen after the # class number gets counted and the waitlist email will be sent. waitlist_status = e.add_to_waitlist() t = Registration(student=u, event=e, date_registered=datetime.now(), waitlist=waitlist_status) t.save() # Email us with the needs of the student. if request.POST["student_needs"] != "": send_mail("(KCDC accommodation form) " + e.title, request.user.email+" requested the following: "+request.POST["student_needs"], request.user.email, ["*****@*****.**"], fail_silently=False) if waitlist_status == False: send_registration_mail(e, 'registered', request.user.email) return HttpResponseRedirect("/classes/response/registered") else: send_registration_mail(e, 'waitlisted', request.user.email) return HttpResponseRedirect("/classes/response/waitlisted") else: return HttpResponseRedirect("/classes/response/error")
def register(request, slug): e = Event.objects.get(slug=slug) u = request.user # if there are no non-cancelled registrations for this user/event and # registration is possible if (is_registered(u, e) == False and is_waitlisted(u, e) == False and e.is_registration_open() == True): # Since the event object will become aware of this registration # as soon as it saves, we need to cache the value. This might bite us? # # Check it: # # There's a class with a size of one with waitlist enabled. If # we save now the check to send the email will happen after the # class number gets counted and the waitlist email will be sent. waitlist_status = e.add_to_waitlist() t = Registration(student=u, event=e, date_registered=datetime.now(), waitlist=waitlist_status) t.save() # Email us with the needs of the student. if request.POST["student_needs"] != "": send_mail("(KCDC accommodation form) " + e.title, request.user.email + " requested the following: " + request.POST["student_needs"], "*****@*****.**", ["*****@*****.**"], fail_silently=False) if waitlist_status == False: send_registration_mail(e, 'registered', request.user.email) return HttpResponseRedirect("/classes/response/registered") else: send_registration_mail(e, 'waitlisted', request.user.email) return HttpResponseRedirect("/classes/response/waitlisted") else: return HttpResponseRedirect("/classes/response/error")
def register_user(user_id, tournament_id): """ Registers a user into a tournament :param user_id: Id of a user :param tournament_id: Id of a tournament :return: True if user is registered and false otherwise """ the_tournament = Tournament.objects.get(id=tournament_id) if the_tournament.current_participants < the_tournament.max_participants: the_user = User.objects.get(id=user_id) reg = Registration() reg.user = the_user reg.tournament = the_tournament reg.save() return True else: return False
def post(self): email = request.args['email'] # Gets or creates a new entry for a hacker hacker, created = Hacker.get_or_create( id=request.args['id'], username=request.args['username'], discriminator=request.args['discriminator']) # If the account exists and is verified return an error if not created and hacker.verified: abort(409, message="Hacker already verified") # Get all registration entries under that email entries = Registration.select().where( fn.Lower(Registration.email) == email.lower()).order_by( Registration.submit_time) if entries.exists(): if entries[0].hacker_discord != None and entries[ 0].hacker_discord != hacker: abort(409, message= "Registration verification started with another hacker") # Start hacker verification hacker.verification = secrets.token_hex(8) hacker.verification_expiration = datetime.datetime.now( ) + datetime.timedelta(hours=1) hacker.save() query = Registration.update(hacker_discord=hacker).where( Registration.email == email) # Email hacker! response = mail.send_verification_email(entries[0], hacker.verification) if response: query.execute() res = jsonify({"status": "Email sent!", "code": 0}) res.status_code = 201 return res else: abort(501, message="Unable to send email") else: abort(404, message="Unable to find registration")
def charge(): def str2date(date_string): """ Returns a datetime date given a valid date_string """ return datetime.datetime.strptime(date_string, "%Y-%m-%d").date() if request.method == 'POST': try: # Amount in pence amount = 2000 customer = stripe.Customer.create( email=request.form['stripeEmail'], card=request.form['stripeToken'] ) charge = stripe.Charge.create( customer=customer.id, amount=amount, currency='gbp', description='Registration' ) registration = Registration( first_name = session['first_name'] , last_name = session['last_name'] , mobile = session['mobile'] , email = session['email'] , dob = str2date(session['dob']) , special_needs = session['special_needs'] , country = session['country'] ) registration.put() email_admin(session) email_user(session) flash("You are now registered!") return redirect(url_for('homepage')) except Exception, e: # TODO: Roll back transaction, registration #print "Payment not processed: %s" % e flash("Payment not processed. %s" % e) return redirect(url_for('new_registration_1'))
def finish_scenario(self, state): Registration(name=state.context['name'], email=state.context['email'], date=state.context['date'], departure=state.context['departure'], destination=state.context['destination'], passengers=state.context['passengers'], comment=state.context['comment'], mobile=state.context['mobile']) log.info( "Выполнена бронь! Отправление {departure}, прибытие {destination}, дата {date}" .format(**state.context))
def on_id_selection(self, section_id): try: reg = Registration(section_id=section_id, student_id=self.__student_id) if reg.save(): section_name = get_section_name(section_id) if section_name: self.__view.print_message( f'Successfully registered {self.__student_name} for {section_name}.' ) else: self.__view.print_message( 'Successfully registered for section.') else: self.__view.print_message(f'Failed to register for section.') except IntegrityError: self.__view.print_message('Unable to register for section.')
def add_registration(): if request.method == 'POST': fullname = request.form.get('fullname') event_id = request.form.get('event_id') if fullname and event_id: manage_code = generate_code(8) db.session.add(Registration(event_id, fullname, manage_code)) db.session.commit() flash( 'You have been successfully registered to the event! Here is your manage code: {}' .format(manage_code)) return redirect('/')
def csv2db(csv_filename): def boolify(s): return {'True':True,'False':False}[s] def dateify(s): return d.strptime(s, "%d/%m/%Y").date() if s != 'none' else None with open(csv_filename) as csvfile: reader = csv.DictReader(csvfile) for row in reader: print row r = Registration( first_name = row['first_name'] , last_name = row['last_name'] , mobile = row['mobile'] , email = row['email'] , sobriety_date = dateify(row['sobriety_date']) , ypaa_committee = row['ypaa_committee'] , fellowship = row['member_of'] , special_needs = row['special_needs'] , country = row['country'] , of_service = boolify(row['of_service']) ) r.put()
def end_scenario(self, state): if self.check_state(state): Registration(departure_city_to_print=state.context['departure_city_to_print'], arrival_city_to_print=state.context['arrival_city_to_print'], departure_date=state.context['date_flight_to_print'], departure_time=state.context['time_flight_to_print'], first_name=state.context['first_name'], last_name=state.context['last_name'], phone=state.context['phone'], flight=state.context['flight_to_print'], email=state.context['email'], number_of_seats=state.context['seats'], comment=state.context['comment']) state.delete() self.first_event = True
def post(self): if typeform.authorize(request.headers["typeform-signature"], request.data): event = request.json vals = typeform.parse_responses(event) try: reg = Registration.create(**vals) entries = Registration.select().where( Registration.email == reg.email).order_by( Registration.submit_time) if entries.exists(): reg.hacker_discord = entries[0].hacker_discord reg.save() except: traceback.print_exc() abort(409, message="Registration not recorded") r = sendy.add_to_mailing_list(reg) if r.status_code == 200: res = jsonify({"status": "Registration recorded"}) res.status_code = 201 return res else: abort(501, message="Registered but unable to send email") abort(401, message="Unauthorized")
def continue_scenario(self, user_id, text, state): """продолжает сценарий""" steps = settings.SCENARIO[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context, flight_schedule=self.FLIGHT_SCHEDULE ): # если хэндлер выернул True next_step = steps[step['next_step']] text_to_send = next_step['text'].format(**state.context) if next_step['next_step']: state.step_name = step['next_step'] else: print(state) print(state.context['email']) print(type(state.context['email'])) Registration(name=state.context['name'], email=state.context['email'], date_flight=state.context['date_flight'], time_flight=state.context['time_flight'], city_out=state.context['city_out'], city_in=state.context['city_in'], sits=state.context['sits'], comment=state.context['comment'], phone=state.context['phone']) state.delete() if 'action' in step: # если в описании шага есть 'action' if step['action'] == 'check_flights_action': if not self.FLIGHT_SCHEDULE[state.context['city_out']][ state.context['city_in']]: self.check_flights_action(user_id, state) text_to_send = 'Введите город отправения: ' elif step['action'] == 'send_image': self.send_image(state, user_id) else: # если хэндлер вернул False text_to_send = step['failure_text'].format(**state.context) if 'fail_action' in step: if step['fail_action'] == 'fail_city_out_action': self.fail_city_out_action(user_id) elif step['fail_action'] == 'fail_city_in_action': self.fail_city_in_action(user_id, state) return text_to_send
def registration(): if request.form: try: person = Registration(firstname=request.form.get("firstname"), lastname=request.form.get("lastname"), address=request.form.get("Address"), email=request.form.get("Email"), password=request.form.get("Password"), phonenumber=request.form.get("Phone Number"), dateofbirth=request.form.get("dateofBirth"), description=request.form.get("message")) db.session.add(person) db.session.commit() return redirect("home-page") except Exception as e: print("Failed to add person") print(e) return render_template('registerPage.html')
def continue_scenario(self, text, state, user_id): steps = settings.SCENARIOS[state.scenario_name][ 'steps'] # в данном случае 'registration' step = steps[state.step_name] handler = getattr( _handlers, step['handler'] ) # из модуля _handlers возвращается соответствующая ф-я if handler(text=text, context=state.context): next_step = steps[step['next_step']] self.sent_step(next_step, user_id, text, state.context) if next_step['next_step']: # switch next step state.step_name = step['next_step'] else: # finish scenario Registration(name=state.context['name'], email=state.context['email']) state.delete() else: text_to_send = step['failure_text'].format(**state.context) self.send_to_text(user_id, text_to_send)
def check_flights_action( self, user_id, state ): # проверка есть ли между городами рейсы, если нет то выдает текст print(state.context) if not self.FLIGHT_SCHEDULE[state.context['city_out']][ state.context['city_in']]: text = 'Между данными городами нет рейсов, попробуйте заново' self.send_text(text, user_id) print(type(state.context['email'])) Registration(name=state.context['name'], email=state.context['email'], date_flight=state.context['date_flight'], time_flight=state.context['time_flight'], city_out=state.context['city_out'], city_in=state.context['city_in'], sits=state.context['sits'], comment=state.context['comment'], phone=state.context['phone']) state.delete() self.start_scenario(scenario_name='ticket', user_id=user_id)
def continue_scenario(self, text, state, user_id): # продолжаем сценарий steps = settings.SCENARIOS[state.scenario_name]['steps'] step = steps[state.step_name] handler = getattr(handlers, step['handler']) if handler(text=text, context=state.context): # next step next_step = steps[step['next_step']] self.send_step(next_step, user_id, text, state.context) if next_step['next_step']: # switch to next step state.step_name = step['next_step'] else: # finish scenario log.info('Пользователь {name} {email} прошел сценарий.'.format(**state.context)) Registration(name=state.context['name'], email=state.context['email']) state.delete() else: text_to_send = step['failure_text'].format(**state.context) self.send_text(text_to_send, user_id)
def register(request, year): event = get_object_or_404(Event, pk=year); places = event.places - len(Guest.objects.filter(event=event)) now = timezone.now() if now < event.round1_opens or (now > event.round1_closes and now < event.round2_opens) or now > event.round2_closes or not places > 0: return render_to_response('registration_closed.html', {'event': event, 'places': places}, context_instance=RequestContext(request)) # If posting a filled out form if request.POST: # Get the forms from the POST data registration_form = RegistrationForm(request.POST) guest_form = GuestForm(request.POST, prefix='guest') avec_form = GuestForm(request.POST, prefix='avec') # If the main guest form and registration specific info was correct if guest_form.is_valid() and registration_form.is_valid(): registration = registration_form.save(commit=False) # If there was an avec if registration.plusone: # If the avec was filled out correctly if avec_form.is_valid(): avec = avec_form.save(commit=False) avec.event = event avec.save() registration.avec = avec else: return render_to_response('registration_form.html', {'registration': registration_form, 'guest': guest_form, 'avec': avec_form, 'year': year, 'desc': event.registration_description} , context_instance=RequestContext(request)) # All good, save guest = guest_form.save(commit=False) guest.event = event guest.save() registration.guest = guest registration.event = event registration.save() data = registration.get_dictionary() send_registration_email(data) return render_to_response('registration_done.html', {'year': year, 'data': data}, context_instance=RequestContext(request)) # If not POST else: registration = Registration() registration.event = event registration_form = RegistrationForm(instance=registration) guest_form = GuestForm(prefix='guest') avec_form = GuestForm(prefix='avec') if places <= 1: registration_form.fields['avecbutton'].widget.attrs['disabled'] = True # If forms not valid or not POST return render_to_response('registration_form.html', {'registration': registration_form, 'guest': guest_form, 'avec': avec_form, 'year': year, 'desc': event.registration_description} , context_instance=RequestContext(request))