我们从Python开源项目中,提取了以下9个代码示例,用于说明如何使用wtforms.SelectField()。
def get_select_field(answer, label, guidance, error_messages): validate_with = get_mandatory_validator(answer, error_messages, 'MANDATORY_RADIO') # We use a custom coerce function to avoid a defect where Python NoneType # is coerced to the string 'None' which clashes with legitimate Radio field # values of 'None'; i.e. there is no way to differentiate between the user # not providing an answer and them selecting the 'None' option otherwise. # https://github.com/ONSdigital/eq-survey-runner/issues/1013 # See related WTForms PR: https://github.com/wtforms/wtforms/pull/288 return SelectField( label=label, description=guidance, choices=build_choices(answer['options']), validators=validate_with, coerce=_coerce_str_unless_none, )
def build_file_select_form(schema): class FileSelectForm(Form): pass for field_name, field_schema in schema.items(): if field_schema['type'] == 'boolean': field = BooleanField() elif field_schema['type'] == 'string': if 'allowed' in field_schema: choices = [(c, c) for c in field_schema['allowed']] field = SelectField(choices=choices) else: field = StringField() elif field_schema['type'] == 'objectid': field = FileSelectField('file') else: raise ValueError('field type %s not supported' % field_schema['type']) setattr(FileSelectForm, field_name, field) return FileSelectForm
def _MakeLocaleChoices(): """Prepare data of available locales for :class:`~wtforms.SelectField`.""" return [(str(l), l.display_name) for l in list_locales()]
def role_id_is_valid(form, field): """ Checks for validity of User's Role :param form: The form which is being passed in :type form: Form :param field : The data value for the 'role' inserted by User :type field : SelectField """ role = Role.query.filter(Role.id == field.data).first() if role is None: raise ValidationError('Role id is invalid')
def get_date_form(answer=None, error_messages=None): """ Returns a date form metaclass with appropriate validators. Used in both date and date range form creation. :param error_messages: The messages during validation :param answer: The answer on which to base this form :return: The generated DateForm metaclass """ class DateForm(Form): day = StringField() year = StringField() validate_with = [OptionalForm()] if not error_messages: date_messages = {} else: date_messages = error_messages.copy() if answer['mandatory'] is True: if 'validation' in answer and 'messages' in answer['validation'] \ and 'MANDATORY_DATE' in answer['validation']['messages']: date_messages['MANDATORY_DATE'] = answer['validation']['messages']['MANDATORY_DATE'] validate_with = [DateRequired(message=date_messages['MANDATORY_DATE'])] if 'validation' in answer and 'messages' in answer['validation'] \ and 'INVALID_DATE' in answer['validation']['messages']: date_messages['INVALID_DATE'] = answer['validation']['messages']['INVALID_DATE'] validate_with += [DateCheck(date_messages['INVALID_DATE'])] # Set up all the calendar month choices for select month_choices = [('', 'Select month')] + [(str(x), calendar.month_name[x]) for x in range(1, 13)] DateForm.month = SelectField(choices=month_choices, default='', validators=validate_with) return DateForm
def get_month_year_form(answer, error_messages): """ Returns a month year form metaclass with appropriate validators. Used in both date and date range form creation. :param answer: The answer on which to base this form :param error_messages: The messages to use upon this form during validation :return: The generated MonthYearDateForm metaclass """ class MonthYearDateForm(Form): year = StringField() validate_with = [OptionalForm()] if answer['mandatory'] is True: error_message = error_messages['MANDATORY_DATE'] if 'validation' in answer and 'messages' in answer['validation'] \ and 'MANDATORY_DATE' in answer['validation']['messages']: error_message = answer['validation']['messages']['MANDATORY_DATE'] validate_with = [DateRequired(message=error_message)] if 'validation' in answer and 'messages' in answer['validation'] \ and 'INVALID_DATE' in answer['validation']['messages']: error_message = answer['validation']['messages']['INVALID_DATE'] validate_with += [MonthYearCheck(error_message)] else: validate_with += [MonthYearCheck()] # Set up all the calendar month choices for select month_choices = [('', 'Select month')] + [(str(x), calendar.month_name[x]) for x in range(1, 13)] MonthYearDateForm.month = SelectField(choices=month_choices, default='', validators=validate_with) return MonthYearDateForm
def test_radio_field(self): radio_json = { "guidance": "", "id": "choose-your-side-answer", "label": "Choose a side", "mandatory": True, "options": [ { "label": "Light Side", "value": "Light Side", "description": "The light side of the Force" }, { "label": "Dark Side", "value": "Dark Side", "description": "The dark side of the Force" }, { "label": "I prefer Star Trek", "value": "I prefer Star Trek" }, { "label": "Other", "value": "Other" } ], "q_code": "20", "type": "Radio" } unbound_field = get_field(radio_json, radio_json['label'], error_messages, self.answer_store) expected_choices = [(option['label'], option['value']) for option in radio_json['options']] self.assertTrue(unbound_field.field_class == SelectField) self.assertTrue(unbound_field.kwargs['coerce'], _coerce_str_unless_none) self.assertEquals(unbound_field.kwargs['label'], radio_json['label']) self.assertEquals(unbound_field.kwargs['description'], radio_json['guidance']) self.assertEquals(unbound_field.kwargs['choices'], expected_choices)
def generate_relationship_form(block_json, number_of_entries, data, error_messages): answer = SchemaHelper.get_first_answer_for_block(block_json) class HouseHoldRelationshipForm(FlaskForm): question_errors = {} def map_errors(self): ordered_errors = [] if self.errors: for answer_id, error_list in self.errors.items(): for errors in error_list: for error in errors: ordered_errors.append((answer_id, error)) return ordered_errors def answer_errors(self, input_id): return [error[1] for error in self.map_errors() if input_id == error[0]] def serialise(self, location): """ Returns a list of answers representing the form data :param location: The location to associate the form data with :return: """ list_field = getattr(self, answer['id']) return serialise_relationship_answers(location, answer['id'], list_field.data) choices = [('', 'Select relationship')] + build_choices(answer['options']) field = FieldList(SelectField( label=answer.get('guidance'), description=answer.get('label'), choices=choices, default='', validators=get_mandatory_validator(answer, error_messages, 'MANDATORY_TEXTFIELD'), ), min_entries=number_of_entries) setattr(HouseHoldRelationshipForm, answer['id'], field) if data: form = HouseHoldRelationshipForm(MultiDict(data)) else: form = HouseHoldRelationshipForm() return form
def add_form_properties(form_class, node_type): """Add fields to a form based on the node and form schema provided. :type node_schema: dict :param node_schema: the validation schema used by Cerberus :type form_class: class :param form_class: The form class to which we append fields :type form_schema: dict :param form_schema: description of how to build the form (which fields to show and hide) """ for prop_name, schema_prop, form_prop in iter_node_properties(node_type): # Recursive call if detects a dict field_type = schema_prop['type'] if field_type == 'dict': assert prop_name == 'attachments' field = attachments.attachment_form_group_create(schema_prop) elif field_type == 'list': if prop_name == 'files': schema = schema_prop['schema']['schema'] file_select_form = build_file_select_form(schema) field = FieldList(CustomFormField(file_select_form), min_entries=1) elif 'allowed' in schema_prop['schema']: choices = [(c, c) for c in schema_prop['schema']['allowed']] field = SelectMultipleField(choices=choices) else: field = SelectMultipleField(choices=[]) elif 'allowed' in schema_prop: select = [] for option in schema_prop['allowed']: select.append((str(option), str(option))) field = SelectField(choices=select) elif field_type == 'datetime': if form_prop.get('dateonly'): field = DateField(prop_name, default=date.today()) else: field = DateTimeField(prop_name, default=datetime.now()) elif field_type == 'integer': field = IntegerField(prop_name, default=0) elif field_type == 'float': field = FloatField(prop_name, default=0.0) elif field_type == 'boolean': field = BooleanField(prop_name) elif field_type == 'objectid' and 'data_relation' in schema_prop: if schema_prop['data_relation']['resource'] == 'files': field = FileSelectField(prop_name) else: field = StringField(prop_name) elif schema_prop.get('maxlength', 0) > 64: field = TextAreaField(prop_name) else: field = StringField(prop_name) setattr(form_class, prop_name, field)