class MultipleFileUploadForm(FlaskForm): uploads = FieldList(FileField("upload"), min_entries=3)
def get_form(self, fill_data=False, form_prefix=''): form_field_info = [] priority = { 'str': 0, 'bool': 1, 'dict': 2, 'list': 3 } for node in sorted(self.children, key=lambda x: priority[x.leaf_type]): field_label = node.label attr = camelify(field_label) field_id = slugify(field_label) sub_form_class = None content = None self.index[attr] = field_label if node.leaf_type == 'str' or node.leaf_type == 'bool': # define form attribute (field) DynamicForm.append_field(attr, TextField(node.label, validators=[DataRequired()], id=field_id)) elif node.leaf_type == 'dict': sub_form_class = self.get_form_class_for_attr(attr) # sub_form_class = type(attr + 'Class', (DynamicForm,), {}) for child in node.children: child_attr = camelify(child.label) self.index[child_attr] = child.label child_field_id = slugify(child.label) sub_form_class.append_field(child_attr, TextField(child.label, validators=[DataRequired()], id=child_field_id)) DynamicForm.append_field(attr, FormField(sub_form_class, id=field_id)) elif node.leaf_type == 'list': first_list = node.children[0] sub_form_class = self.get_form_class_for_attr(attr) for child in first_list.children: child_attr = camelify(child.label) self.index[child_attr] = child.label child_field_id = slugify(child.label) sub_form_class.append_field(child_attr, TextField(child.label, validators=[DataRequired()], id=child_field_id)) DynamicForm.append_field(attr, FieldList(FormField(sub_form_class, id=field_id))) form_field_info.append( { 'node': node, 'attr': attr, 'sub_form_class': sub_form_class, # 'content': content, # 'field_obj': field_obj }) form = DynamicForm() # define field values if fill_data: for field_d in form_field_info: attr = field_d['attr'] node = field_d['node'] sub_form_class = field_d['sub_form_class'] if node.leaf_type == 'str': getattr(form, attr).data = node.leaf_content elif node.leaf_type == 'bool': getattr(form, attr).data = str(node.leaf_content) elif node.leaf_type == 'dict': for child in node.children: child_attr = camelify(child.label) getattr(getattr(form, attr), child_attr).data = child.leaf_content elif node.leaf_type == 'list': field_list = getattr(form, attr) create_entries = len(field_list.entries) == 0 for i, node_list in enumerate(node.children): child_form = sub_form_class() for child in node_list.children: child_attr = camelify(child.label) setattr(child_form, child_attr, child.leaf_content) if create_entries: # print('Create entry', i) field_list.append_entry(child_form) # else: # print('No need to create entry', i) # field_list.entries[i] = child_form return form
class StoreBaseForm(FlaskForm): class Meta: locales = ('de_DE', 'de') name = StringField(label=_('Name'), validators=[ validators.DataRequired( message=_('Bitte geben Sie einen Namen an.')) ]) category = CategoryField(label=_('Art des Geschäfts')) source_text = StringField(label=_('Woher kommt die Information?')) source_url = StringField( label=_('Woher kommt die Information (Ergänzender Link)?'), validators=[ validators.URL( message='Bitte geben Sie eine valide URL ein (oder gar nichts)' ), validators.Optional() ]) company = StringField(label=_('Unternehmen')) address = StringField( label=_('Straße und Hausnummer'), validators=[ validators.DataRequired( message=_('Bitte geben Sie eine Straße und Hausnummer an.')) ]) postalcode = StringField( label=_('Postleitzahl'), validators=[ validators.DataRequired( message=_('Bitte geben Sie eine Postleitzahl an.')) ]) locality = StringField( label=_('Ort'), validators=[ validators.DataRequired(message=_('Bitte geben Sie einen Ort an.')) ]) website = StringField( label=_('Website'), validators=[ validators.url(message='Bitte geben Sie eine URL an'), validators.Optional() ], ) email = StringField( label=_('E-Mail'), validators=[ validators.email(message='Bitte geben Sie eine E-Mail an'), validators.Optional() ], ) phone = StringField(label=_('Telefon')) mobile = StringField(label=_('Mobiltelefon')) fax = StringField(label=_('Fax')) description = TextAreaField(label='Beschreibung') all_switch = BooleanField(label='Geschäft hat geöffnet') opening_times_all = FieldList(FormField(OpeningTimeForm), label='Öffnungszeiten', min_entries=0) delivery = BooleanField(label='Lieferung') pickup = BooleanField(label='Abholung') onlineshop = BooleanField(label='Onlineshop') delivery_switch = BooleanField(label='Abweichende Lieferzeiten') opening_times_delivery = FieldList(FormField(OpeningTimeForm), label='Öffnungszeiten', min_entries=0) pickup_switch = BooleanField(label='Abweichende Abholzeiten') opening_times_pickup = FieldList(FormField(OpeningTimeForm), label='Öffnungszeiten', min_entries=0) logo = ExtendedFileField( label='Logo', validators=[ ValidateMimeType( mimetypes=[ 'image/jpeg', 'image/png', 'image/svg+xml', 'image/gif' ], allow_empty=True, message='Bitte ein PNG-, JPG- oder SVG-Bild hochladen!') ]) picture = ExtendedFileField( label='Bild', validators=[ ValidateMimeType( mimetypes=['image/jpeg', 'image/png', 'image/svg+xml'], allow_empty=True, message='Bitte ein PNG-, JPG- oder SVG-Bild hochladen!') ]) submit = SubmitField(_('speichern'))
class ExerciseForm(NoCsrfForm): exname = StringField('Exercise Name') entries = FieldList(FormField(SetForm, default=lambda: Entry()), min_entries=1)
class FormBuilder(Form, FormMixin): buttons = FieldList(FormField(dynamic_scriptform(folderpath))) forms = FieldList(FormField(FormConfig))
class SignatureForm(FlaskForm): """Signature Form Class """ signatures = FieldList(BooleanField(''), min_entries=1)
class GameDetails(FlaskForm): """ Used by new and edit game this contains all the data for each game. Note that a FieldList is used to show each player details in the game. Validation ensures that duplicate names cannot be entered and only one person can be chosen as the game booker. Requires __init__ function so that validation can check if the right number of players are checked by the user. TO DO: validation for Game Date, or pull down to select from calender. Implement titling of player names (first letter is a capital). There is also a bad flaw in the DB design as a player name could clash with a another key not associated with player name, needs redesign before production use. for example, don't enter a player name as 'Cost of Game'! TO DO: NB: CFFA only supports GBP, hardcoded currency behaviour. Attributes ---------- gamecost : FloatField Cost in GBP for the game booking. Eventually converted to Decimal128 for currency DB storage. gamedate : DateField DateTime.DateTime is the data attribute in this input field playerlist : `FieldList` of `PlayerInGame` obj of `FlaskForm. Note the minimum number of rows is 10 when displaying the form. Logic will pad out empty rows if default population does not cover sufficient rows. submit : SubmitField Standard submit button. """ gamecost = FloatField('Cost of Game', [validators.required()]) gamedate = DateField('Game Date', [validators.required()]) playerlist = FieldList(FormField(PlayerInGame), min_entries=10) submit = SubmitField('Submit') def __init__(self, number_of_expected_players, *args, **kwargs): """ Requires init so that number_of_expected_players can be part in the class and checked against during validation to ensure the right number of players are checked. This logic counts any guests specified as well. Parameters ---------- number_of_expected_players : `int` Set by the user in the form AddGameNoPlayers *args : *args Passed through to the FlaskForm **kwargs : **kwargs Passed through to the FlaskForm """ FlaskForm.__init__(self, *args, **kwargs) # formdata = hmmm add at it works but now has broken new_game -formdata override removed when page has own # entry point. # FlaskForm.__init__(self, formdata=None, *args, **kwargs) self.number_of_expected_players = number_of_expected_players def validate(self): """ Checks only for: a) right number of players selected, including guest numbers. (b) There must be one booker selected. Note that a booker does not have to play the game """ if not super().validate(): return False result = True selected_player_list = set() number_of_selected_players = 0 count_bookers = 0 for field in [self.playerlist.data]: for x in field: if x.get("playedlastgame"): if x.get("playername") in selected_player_list: self.playerlist.errors.append( "Duplicate player provided - check player names!") result = False elif x.get( "playername") == "" or x.get("playername") is None: self.playerlist.errors.append( "Cannot play an unnamed player. Please enter a name!" ) result = False else: selected_player_list.add(x.get("playername")) number_of_selected_players += 1 # don't need to play a game to have a guest # print("GameDetails form: player name ", x.get("playername"), " has ", x.get("guests"), " guests") number_of_selected_players += x.get("guests", 0) if x.get("pitchbooker"): count_bookers += 1 if self.number_of_expected_players > 0: if self.number_of_expected_players != number_of_selected_players: our_error = "Unexpected number of players. " + \ str(number_of_selected_players) + \ " selected, but " + \ str(self.number_of_expected_players) + \ " expected!" self.playerlist.errors.append(our_error) result = False if count_bookers != 1: self.playerlist.errors.append( "There must be one player who booked the pitch!") result = False return result
class AdminUsers(FlaskForm): user_details = FieldList(FormField(AdminUsersDetails)) submit = SubmitField("Update Users")
class envForm(FlaskForm ): #TODO:BORRAR ESTE Y EL DE ABAJO SI FINALMENTE NO LO USO envs = FieldList(FormField(singleEnv), min_entries=len(env_names)) submit = SubmitField('Submit')
class ShiftsForm(Form): phone = StringField('phone_no') shifts = FieldList(FormField(ShiftForm)) submit = SubmitField('Update shifts')
class ExamMarkForm(FlaskForm): marks = FieldList(StringField('Mark'), min_entries=5) submit = SubmitField('Submit')
class CellForm(BaseForm): CNODE_MIN = 3 name = StringField( label=u'セル名', validators=[ validators.DataRequired(), validators.Length(max=256), validators.Regexp('^\w+$') ], ) type = SelectField( label=u'セル種別', choices=[(tp, tp) for tp in Cell.CELL_TYPE], ) comment = TextAreaField(label=u'コメント', ) nodes = FieldList( FormField(CellNodeForm), label=u'サーバ', min_entries=CNODE_MIN, ) def __init__(self, formdata=None, obj=None, prefix='', data=None, meta=None, **kwargs): super(CellForm, self).__init__(formdata, obj, prefix, data, meta, **kwargs) self.update_nodes() def update_nodes(self): nodes = Node.select() for cnode in self.nodes: cnode['node'].choices = [(n.id, n.hostname) for n in nodes] def populate_obj(self, obj): for name, field in iteritems(self._fields): if not isinstance(field, FieldList): field.populate_obj(obj, name) def populate_cellnodes(self, nodes): while len(self.nodes) > 0: self.nodes.pop_entry() for n in nodes: ent = self.nodes.append_entry(n) ent['node'].data = n.node.id ent['node_id'].data = n.id self.update_nodes() def exists_cnode(self, cnode): for ent in self.nodes: if ent['node_id'].data.isnumeric() and\ int(ent['node_id'].data) == cnode.id: return True return False def get_hostname(self, host_id): if len(self.nodes) == 0: return None choices = self.nodes[0]['node'].choices for ch in choices: if ch[0] == host_id: return ch[1] return None def _save_cell(self, cell): self.populate_obj(cell) try: cell.save() return True except IntegrityError as e: logger.error(str(e)) self.name.errors.append(e.message) def _save_cnode(self, nform, nid, idx, cell): cnode = CellNode() nform.form.populate_obj(cnode) cnode.id = nid cnode.no = idx cnode.cell = cell try: cnode.save() return True except IntegrityError as e: logger.error(str(e)) if string.find(e.message, 'tcp') >= 0: nform.form.tcp_port.errors.append(e.message) elif string.find(e.message, 'udp') >= 0: nform.form.udp_port.errors.append(e.message) else: self.name.errors.append(e.message) def create(self): with database.database.atomic() as txn: cell = Cell() if not self._save_cell(cell): txn.rollback() return False for idx, nform in enumerate(self.nodes): if not self._save_cnode(nform, None, idx, cell): txn.rollback() return False try: cell.deploy_conf() except Exception as e: logger.exceptions(e) return True def update(self, id): with database.database.atomic() as txn: cell = Cell().get(Cell.id == id) if not self._save_cell(cell): txn.rollback() return False for cnode in cell.nodes: if not self.exists_cnode(cnode): cnode.delete().where(CellNode.id == cnode.id).execute() for idx, nform in enumerate(self.nodes): node_id = nform.form['node_id'].data nid = (int(node_id) if node_id is not None and node_id.isnumeric() else None) if not self._save_cnode(nform, nid, idx, cell): txn.rollback() return False try: cell.deploy_conf() except Exception as e: logger.exceptions(e) return True def _pop_cnode(self, num): cnode_list = [] for i in range(num): cnode = CellNode() nform = self.nodes.pop_entry() nform.form.populate_obj(cnode) cnode_list.insert(0, cnode) return cnode_list def _push_cnode(self, cnode_list): node_list = Node.select() for cnode in cnode_list: nform = self.nodes.append_entry(cnode) nform['node'].choices = [(n.id, n.hostname) for n in node_list] if cnode._data.get('node') is not None: nform['node'].data = cnode.node.id def delete_cnode_by_no(self, no): if len(self.nodes) <= CellForm.CNODE_MIN: return cnode_list = self._pop_cnode(len(self.nodes) - no - 1) self.nodes.pop_entry() self._push_cnode(cnode_list) def insert_cnode_by_no(self, no): cnode_list = self._pop_cnode(len(self.nodes) - no) cnode_list.insert(0, CellNode()) self._push_cnode(cnode_list) @classmethod def delete(cls, id): with database.database.atomic(): cell = Cell.get(Cell.id == id) try: from .ras.forms import RasTargetForm RasTargetForm.delete_nonexists_target('cell', cell.name) except Exception as e: logger.exception(e) cell.delete_instance() CellNode.delete().where(CellNode.cell == id).execute()
class TeachersAvailable(FlaskForm): subjectsAvailable = FieldList(FormField(TeacherRange), min_entries=1) submit = SubmitField('Apply') clearAll = SubmitField('Clear All')
class NodesForm(FlaskForm): nodes = FieldList(FormField(NodeForm), min_entries=2, max_entries=7)
class CardSetForm(FlaskForm): card_set_name = StringField("Card Set Name", validators=[DataRequired()]) cards = FieldList(FormField(CardForm), min_entries=1) measure = StringField("Measure", validators=[DataRequired()]) submit = SubmitField("Submit")
class algosForm(FlaskForm): algos = FieldList(FormField(singleAlgo), min_entries=len(algo_names)) submit = SubmitField('Submit')
class StudyForm(FlaskForm): name = StringField("Name", validators=[DataRequired()]) desc = TextAreaField("Description", validators=[Optional(), Length(max=400)]) image = FileField( "Image", validators=[FileAllowed(["jpg", "png", ".gif"], "Images only")], ) card_set_x = QuerySelectField("Card Set for x-axis", validators=[DataRequired()]) card_set_y = QuerySelectField("Card Set for y-axis", validators=[DataRequired()]) data_values = SelectField( "Data Values", choices=[("0", 0), ("1", 1), ("2", 2)], validators=[DataRequired()], default=2, ) data_value_labels = FieldList(StringField("Data Value Label"), min_entries=2) number_of_columns = SelectField( "Number of Columns", choices=[("2", 2), ("3", 3), ("4", 4), ("5", 5)], validators=[DataRequired()], default=2, ) number_of_rows = SelectField( "Number of Rows", choices=[("2", 2), ("3", 3), ("4", 4), ("5", 5)], validators=[DataRequired()], ) user_group = QuerySelectField("User Study Participant Group", validators=[DataRequired()]) start_date = DateField( "Study Start Date", id="datepick", format="%Y-%m-%d", validators=[DataRequired()], ) end_date = DateField( "Study End Date", id="datepick", format="%Y-%m-%d", validators=[DataRequired()], ) submit = SubmitField("Create") def validate(self): result = True if not super(StudyForm, self).validate(): result = False if self.end_date.data and self.start_date.data: if self.end_date.data < self.start_date.data: msg = "The end date cannot be before the start date." self.end_date.errors.append(msg) result = False if self.start_date.data < date.today(): msg = "The start date cannot be in the past." self.start_date.errors.append(msg) result = False if self.end_date.data < date.today(): msg = "The end date cannot be in the past." self.end_date.errors.append(msg) result = False if self.card_set_x.data == self.card_set_y.data: msg = ( "Card Set for x-axis cannot have the same value as Card Set for y-axis." ) self.card_set_x.errors.append(msg) result = False return result
class LineupBoxForm(FlaskForm): bop = FieldList(FormField(BoxOrderPosForm))
class CreatePollForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) options = FieldList(StringField()) submit = SubmitField('Create')
class OrderInputForm(FlaskForm): organization = StringField("Enter your organization name: ", validators=[Required()]) breads = FieldList(FormField(OrderBreadForm), min_entries=1)
class MainForm(FlaskForm): """Parent form.""" step01 = FieldList(FormField(StepForm), min_entries=1, max_entries=50)
class PlanningFormProcessor(Form): libelle = StringField('Libellé', [validators.Length(min=5, max=40)]) plages = FieldList(FormField(PlageFormProcess), "plages", None, 5, 10)
class ExpJsonListForm(FlaskForm): category = StringField('Category', validators=[DataRequired()]) exps = FieldList(FormField(ExpJsonForm), min_entries=3) submit_exp = SubmitField('Run Comparisons')
class CycleFormProcessor(Form): libelle = StringField('Libellé', [validators.Length(min=5, max=40)]) plannings = FieldList(FormField(CyclePlanningFormProcessor), "plannings", None, 5, 14)
class PlansForm(StripWhitespaceForm): email = TextField("Email", [validators.Email(), validators.DataRequired()]) title = FieldList(StringField("Title", [validators.DataRequired()]), min_entries=1) company_name = TextField("Company Name") slogan = TextField("Slogan") instant_payment = FieldList(TextField("Up-Front Payment", default=False), min_entries=1) uuid = FieldList(StringField(), min_entries=1) subscription = FieldList(TextField("Subscription", default=False), min_entries=1) private = FieldList(TextField("Private Plan", default=False), min_entries=1) note_to_seller_required = FieldList(TextField("Require note from customer", default=False), min_entries=1) # Allow seller to say what additional information they need note_to_buyer_message = FieldList( TextAreaField(u"Note to buyer", [validators.optional(), validators.length(max=500)])) days_before_first_charge = FieldList( StringField("Days before first charge")) trial_period_days = FieldList(StringField("Trial number of days")) sell_price = FieldList(FloatField("Up-front Price", [validators.optional()]), min_entries=1) interval_amount = FieldList(FloatField("Reccuring Amount", [validators.optional()]), min_entries=1) interval_unit = FieldList(StringField("Interval Unit", [validators.optional()]), min_entries=1) selling_points = FieldList( FieldList( StringField("Unique Selling Point", [validators.DataRequired()]), min_entries=1, ), min_entries=1, ) images = UploadSet("images", IMAGES) image = FieldList( FileField(validators=[FileAllowed(images, "Images only!")]), min_entries=1) position = FieldList( IntegerField("Position", [validators.optional()], default=0)) cancel_at = FieldList( StringField("Cancel at", [validators.optional()], default=False)) description = FieldList( StringField("Description", [validators.optional()], default=False))
class Intent(FlaskForm): name = StringField('Nome Entidade', validators=[DataRequired()]) response = FieldList(StringField('Respostas', validators=[required()])) submit = SubmitField('Criar uma nova Inteção')
class CreateEachPollQuestionForm(Form): questionTitle = StringField('Question Title', validators=[DataRequired()]) answerList = FieldList(FormField(CreatePollAnswerForm), min_entries=0) questionType = HiddenField('type')
class UserGroupForm(FlaskForm): name = StringField("User Group Name", validators=[DataRequired()]) users = FieldList(label="Users", unbound_field=FormField(UserForm), min_entries=1) submit = SubmitField("Create")
class BulkTaskDropboxImportForm(Form): form_name = TextField(label=None, widget=HiddenInput(), default='dropbox') files = FieldList(TextField(label=None, widget=HiddenInput())) def get_import_data(self): return {'type': 'dropbox', 'files': self.files.data}
class BrokenForm(FlaskForm): text_fields = FieldList(StringField()) file_fields = FieldList(FileField())