class SettingsForm(FlaskForm): name: fields.Field = StringField(lazy_gettext('Site Name')) description: fields.Field = StringField(lazy_gettext('Site Description')) avatar: fields.Field = StringField(lazy_gettext('Avatar URL')) cover_url: fields.Field = StringField(lazy_gettext('Cover Image URL')) locale: fields.Field = fields.SelectField( lazy_gettext('Language'), choices=[ ('en', lazy_gettext('English')), ('zh_Hans_CN', lazy_gettext('Chinese')), ], default='en', ) google_site_verification: fields.Field = StringField( lazy_gettext('Google Site Verification Code')) disqus_shortname: fields.Field = StringField( lazy_gettext('Disqus Shortname')) sociallinks: fields.Field = fields.FieldList(fields.FormField(SocialLink), lazy_gettext('Social Links'), min_entries=1) icp: fields.Field = StringField(lazy_gettext('ICP No.')) links: fields.Field = fields.FieldList(fields.FormField(FriendLink), lazy_gettext('Friend Links'), min_entries=1) @classmethod def from_local(cls) -> "SettingsForm": return cls(data=g.site)
class ChildEventForm(BaseForm): name = fields.StringField(('Name'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=( "Field cannot be longer than %(max)d characters."))]) description = fields.TextAreaField('Description') media = fields.FieldList(fields.FormField(MediaForm), min_entries=5) parent_event_id = fields.HiddenField() start_datetime = fields.DateTimeField('Start Date Time', [validators.Required()]) end_datetime = fields.DateTimeField('End Date Time', [validators.Required()]) contact_info = fields.FormField(ContactInfo) custom_info = fields.FieldList(fields.FormField(CustomInfo), min_entries=2) pass
class RuleForm(BaseForm): name = fields.StringField('Rule name', [DataRequired(), Length(max=64)]) conditions = fields.FieldList(fields.FormField(ConditionForm), min_entries=1) actions = fields.FieldList(fields.FormField(ActionForm), min_entries=1) def __init__(self, *args, **kwargs): self.rule = rule = kwargs.pop('rule', None) formdata = args[0] if args else None super(RuleForm, self).__init__(*args, **kwargs) if rule: self.name.process(formdata, rule.name) def validate_name(self, field): if self.rule and (field.data == self.rule.name): return try: Rule.query.filter_by(name=field.data, meeting=g.meeting, rule_type=g.rule_type).one() raise ValidationError('Name must be unique') except NoResultFound: pass def validate_actions(self, field): condition_fields = set([i['field'] for i in self.conditions.data]) action_fields = set([i['field'] for i in self.actions.data]) if condition_fields & action_fields: raise ValidationError('Action fields should be different ' 'from condition fields') if len(action_fields) != len(self.actions.data): raise ValidationError('Actions fields should be different') def save(self): rule = self.rule or Rule(meeting=g.meeting) rule.name = self.name.data rule.rule_type = g.rule_type # if edit, delete all conditions and actions for this rule and their # corresponding values if rule.id: Condition.query.filter_by(rule=rule).delete() Action.query.filter_by(rule=rule).delete() for condition_form in self.conditions: condition_form.save(rule) for action_form in self.actions: action_form.save(rule) if not rule.id: db.session.add(rule) db.session.commit()
class HomeInputForm(form.Form): majors =fields.SelectMultipleField(label="majors", validators=[validators.DataRequired()]) specs =fields.SelectMultipleField(label="specs") firstQuarter = fields.SelectField(label="start quarter for scheduling", default=(0,0)) quarterCreditDefault = fields.SelectField(label="default maximum credits per quarter" ,validators=[validators.DataRequired()], choices=[(x,x) for x in range(30)], default=(16,16)) quarterCredits = fields.FieldList(fields.FormField(QuarterCreditForm), label="maximum credits per quarter", validators=[validators.Optional()], min_entries=1, max_entries=15) next = fields.SubmitField('next') def validate_on_submit(self): """ Checks if form has been submitted and if so runs validate. This is a shortcut, equivalent to ``form.is_submitted() and form.validate()`` """ return self.is_submitted() and self.validate() def is_submitted(self): """ Checks if form has been submitted. The default case is if the HTTP method is **POST**. """ return request and request.method == "POST"
def conv_List(self, model, field, kwargs): kwargs = { 'validators': [], 'filters': [], } unbound_field = self.convert(model, field.field, {}) return f.FieldList(unbound_field, min_entries=0, **kwargs)
class SecurityQuestionRegisterForm(ExtendedRegisterForm): questions = fields.FieldList( fields.SelectField(), 'questions', None, min_entries=1, max_entries=5, )
class ReceiptForm(ModelForm): class Meta: model = Receipt name = fields.StringField("Name", [va.length(min=1)]) amount = fields.DecimalField("Decimal", [va.NumberRange(min=0)]) tax = fields.DecimalField("Decimal", [va.NumberRange(min=0)]) receipt_items = fields.FieldList(fields.FormField(ReceiptItemForm))
class UserForm(form.Form): shib_id = ShibIDField('Shibboleth ID') first_name = fields.StringField('First name', [validators.DataRequired()]) last_name = fields.StringField('Last name', [validators.DataRequired()]) email = fields.StringField( 'Email', [validators.Optional(), validators.Email()]) phone_numbers = fields.FieldList(fields.StringField(''), min_entries=1) fax_numbers = fields.FieldList(fields.StringField(''), min_entries=1) role = fields.StringField('Role') job_title = fields.StringField('Job Title') organization_id = fields.SelectField('Organization') groups = fields.FieldList(ReadonlyStringField('')) active = fields.BooleanField('Active', default=lambda: True) last_changed_by = ReadonlyStringField('Last Changed By', [validators.Optional()]) last_changed_on = ReadonlyDateTimeField('Last Changed On', [validators.Optional()])
class PageForm(form.Form): name = fields.TextField('Name', [validators.required(), validators.length(max=500)]) url = fields.TextField('URL', [validators.required(), validators.URL(require_tld=False), validators.length(max=1024)]) preview_urls = fields.FieldList(fields.TextField('Additional preview URLs', [validators.URL(require_tld=False), validators.length(max=1024)])) def validate(self): self.url.data = add_protocol(self.url.data) for ix in range(len(self.preview_urls)): self.preview_urls[ix].data = add_protocol(self.preview_urls[ix].data) return form.Form.validate(self)
class TeamForm(BaseForm): importfile = fields.FileField(('Excel/CSV')) name = fields.StringField(('Team Name'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=( "Field cannot be longer than %(max)d characters."))]) sport = fields.SelectField(u'Sport', choices=[(key, value) for key, value in constants.SPORTS_LIST.items()], default='others') logo = fields.FileField('Logo') category = fields.SelectField(u'Category', choices=[(key, value) for key, value in constants.CATEGORY_DICT.items()], default='open') new_player = fields.FieldList(fields.FormField(PlayerForm), min_entries=1) #players = fields.FieldList(fields.FormField(MyForm)) pass
def conv_List(self, model, field, kwargs): if isinstance(field.field, ReferenceField): return ModelSelectMultipleField(model=field.field.document_type, **kwargs) if field.field.choices: kwargs['multiple'] = True return self.convert(model, field.field, kwargs) unbound_field = self.convert(model, field.field, {}) kwargs = { 'validators': [], 'filters': [], } return f.FieldList(unbound_field, min_entries=0, **kwargs)
class datasetForm(FlaskForm): title = f.StringField('Name of this dataset', [ v.InputRequired(r('dataset name')), v.length(5, 250, 'Dataset title must be between 5 and 250 characters long') ]) description = f.TextAreaField('Dataset description', [ v.length( max=65500, message='Description can not be longer than 65,500 characters.') ]) files = f.FieldList(f.FileField('Custom dataset file from your computer'), max_entries=100) newFile = f.SubmitField('Add a new dataset file from your computer', render_kw=w3Button) removeFile = f.SubmitField('Remove the last dataset file entry', render_kw=w3Button) URLs = f.FieldList(f5.URLField('URL of dataset of file', [v.URL('Please enter a valid URL')]), max_entries=100) newURL = f.SubmitField('Add a new dataset URL', render_kw=w3Button) removeURL = f.SubmitField('Remove the last URL entry', render_kw=w3Button) uploadDataset = f.SubmitField('Upload the dataset', render_kw=w3Button)
def conv_List(self, model, field, kwargs): if isinstance(field.field, ReferenceField): return ModelSelectMultipleField(model=field.field.document_type, **kwargs) if field.field.choices: kwargs["multiple"] = True return self.convert(model, field.field, kwargs) field_args = kwargs.pop("field_args", {}) unbound_field = self.convert(model, field.field, field_args) unacceptable = { "validators": [], "filters": [], "min_entries": kwargs.get("min_entries", 0), } kwargs.update(unacceptable) return f.FieldList(unbound_field, **kwargs)
class PlaygroundForm(BaseForm): name = fields.StringField(('Name'), [validators.Required(), validators.Length(max=FIELD_MAXLENGTH, message=( "Field cannot be longer than %(max)d characters."))]) sport = fields.SelectField(u'Sport', choices=[(key, value) for key, value in constants.SPORTS_LIST.items()], default='others') locality = fields.StringField(('Area/Locality'), [validators.Required(), validators.Length(max=NAME_FILED_MAXLENGTH, message=( "Field cannot be longer than %(max)d characters."))]) city = fields.StringField(('City'), [validators.Required(), validators.Length(max=NAME_FILED_MAXLENGTH, message=( "Field cannot be longer than %(max)d characters."))]) description = fields.TextAreaField('Description') featured = fields.BooleanField('Featured') media = fields.FieldList(fields.FormField(MediaForm), min_entries=1) address = fields.FormField(Address) contact_info = fields.FormField(ContactInfo) locality_id = fields.HiddenField() #custom_info = fields.FieldList(fields.FormField(CustomInfo), min_entries=2) pass
class datasetEditorForm(FlaskForm): columnSelections = f.FieldList(f.FormField(SelectForm)) finalText = f.TextAreaField( 'Edit your dataset to remove unwanted data', [ v.length(min=1000, message= 'The final text cannot be shorter than 1,000 characters.') ], render_kw={ 'rows': '20', 'cols': '100', 'placeholder': 'Click \\"refresh dataset text\\"; to automatically fill out this field' }) datasetRefresh = f.SubmitField('Refresh dataset text', render_kw=w3Button)
class OTRSubmissionForm(BJSubmissionForm): introduction = fields.TextAreaField( 'General introduction/description', validators=[DataRequired()] ) pictures = fields.FieldList( fields.FormField(PictureForm), min_entries=config.MAX_PICTURES, max_entries=config.MAX_PICTURES, validators=[Optional()] ) verification_error = ("Something went wrong verifying this " "email and username combination. If you haven't " "commented at Balloon-Juice before, go comment in an " "active thread, wait for it to get approved, and come " "submit your pictures again. Alternatively, email your " "pictures to [email protected]" )
class BaseProductForm(Form): product_id = fields.StringField(_name='id') active = fields.BooleanField() attributes = fields.FieldList(fields.StringField(), min_entries=1, max_entries=5) caption = fields.StringField() deactivate_on = fields.DateField() description = fields.TextAreaField() images = fields.MultipleFileField() livemode = fields.BooleanField() product_metadata = fields.TextAreaField(_name='metadata') name = fields.StringField() package_dimensions = fields.FormField(PackageDimensionsForm) shippable = fields.BooleanField() product_type = MyRadioField(choices=[('service', 'service'), ('good', 'good')]) url = fields.StringField()
def construct_form(meta): subfs = OrderedDict() for field in meta: kind = field['kind'] name = field['name'] label = field['label'] required = field['required'] checkers = [] if required: if kind == 'int': checkers.append(validators.InputRequired('这个字段必填')) else: checkers.append(validators.Required('这个字段必填')) else: checkers.append(validators.Optional()) if kind == 'int': f = html5.IntegerField(label, description='输入' + label, validators=checkers) elif kind == 'bool': f = fields.BooleanField(label, description=label, validators=[validators.Optional()]) elif kind == 'string': f = fields.StringField(label, description='输入' + label, validators=checkers) elif kind == 'url': checkers.append(validators.URL()) f = html5.URLField(label, description='输入' + label, validators=checkers) else: raise NotImplementedError('%s kind not supported' % kind) subfs[name] = f subform_class = type(b'_Registry_Sub_Form', (WTForm, ), subfs) value_field = fields.FieldList(fields.FormField(subform_class), default=[{}]) form_class = type(b'_Registry_Form', (Form, ), OrderedDict(value=value_field)) return form_class
class EditRegistryMetaForm(Form): key = fields.StringField('关键字', description='输入关键字', validators=[validators.Required('关键字不能为空')]) name = fields.StringField('中文名称', description='输入中文名称', validators=[validators.Required('中文名称不能为空')]) meta = fields.FieldList(fields.FormField(RegistryMetaForm), default=[{}]) def validate_key(self, field): from oj.models import RegistryModel if g.registry and g.registry.key == field.data: return if RegistryModel.query.get(field.data): raise ValidationError('关键字已存在') def validate_meta(self, fields): names = [f['name'] for f in fields.data] if not names: raise ValidationError('不能没有字段啊') if len(names) != len(set(names)): raise ValidationError('字段英文名不能重复')
def conv_List(self, model, field, kwargs): if isinstance(field.field, ReferenceField): return ModelSelectMultipleField(model=field.field.document_type, **kwargs) if getattr(field.field, "queryset", None): return ModelSelectMultipleField(model=field.field.queryset, **kwargs) if isinstance(field.field, StringField) and getattr( field, "queryset", None) and getattr(field.field, "queryset", None): return TagsField(**kwargs) if field.field.choices: kwargs['multiple'] = True return self.convert(model, field.field, kwargs) field_args = kwargs.pop("field_args", {}) unbound_field = self.convert(model, field.field, field_args) unacceptable = { 'validators': [], 'filters': [], 'min_entries': kwargs.get('min_entries', 0) } kwargs.update(unacceptable) return f.FieldList(unbound_field, **kwargs)
class CompaniesNames(Form): items = f.FieldList(f.FormField(CompanyName), min_entries=10)
class EditorForm(FlaskForm): alteration = fields.FieldList(fields.FormField(AlterationForm)) assertion = fields.FieldList(fields.FormField(AssertionForm)) source = fields.FieldList(fields.FormField(SourceForm))
class CommandMessagesForm(Form): items = f.FieldList(f.FormField(CommandMessageForm))
class PatientForm(Form): # BASIC ID # full_name will be deprecated soon full_name = fields.TextField( _('Full legal name'), validators=[Optional(), validators.Length(max=128)]) first_name = fields.TextField( _('First name'), [DataRequired(), validators.Length(max=64)] ) middle_name = fields.TextField(_('Middle name'), [validators.Length(max=64)]) last_name = fields.TextField( _('Last name'), [DataRequired(), validators.Length(max=64)] ) dob = fields.DateField(_('Date of birth')) ssn = fields.TextField( _('Social security number'), [Optional(), validators.Length(max=11), validate_ssn] ) # CONTACT email = fields.TextField( _('Email address'), validators=[Optional(), Email(), validators.Length(max=64)] ) phone_numbers = fields.FieldList(fields.FormField( PhoneNumberForm )) addresses = fields.FieldList(fields.FormField( AddressForm )) has_transport_yn = fields.SelectField( _("Do you have transportation?"), choices=CONSTANTS.YN_CHOICES, default="", ) emergency_contacts = fields.FieldList(fields.FormField( EmergencyContactForm )) # DEMOGRAPHIC/SOCIAL HISTORY gender = fields.SelectField( _('Gender'), choices=CONSTANTS.GENDER_CHOICES, default=_('No Answer') ) transgender = fields.SelectField( _('Transgender'), choices=CONSTANTS.TRANSGENDER_CHOICES, default="", ) race = fields.SelectField( _('Race'), choices=CONSTANTS.RACE_CHOICES, default="", ) race_other = fields.TextField( _('Please specify other race'), [Optional(), validators.Length(max=32)] ) ethnicity = fields.SelectField( _('Ethnicity'), choices=CONSTANTS.ETHNICITY_CHOICES, default="", ) ## testing out radio buttons in the general form languages = fields.SelectMultipleField( _('Language'), choices=CONSTANTS.LANGUAGE_CHOICES, default="", ) # languages = fields.RadioField( # _('Language'), # choices=CONSTANTS.LANGUAGE_CHOICES, # default="", # ) languages_other = fields.TextField( _('Please specify other languages'), [Optional(), validators.Length(max=64)] ) has_interpreter_yn = fields.SelectField( _("Do you have access to an interpreter?"), choices=CONSTANTS.YNNA_CHOICES, default="" ) education_level = fields.TextField( _("What is your highest level of education?"), [validators.Length(max=16)] ) marital_status = fields.SelectField( _('Marital status'), choices=CONSTANTS.MARITAL_STATUS_CHOICES, default="", ) veteran_yn = fields.SelectField( _('Are you a veteran of the United States?'), choices=CONSTANTS.YN_CHOICES, default="", ) housing_status = fields.SelectField( _('Living situation'), choices=CONSTANTS.HOUSING_STATUS_CHOICES, default="", ) housing_status_other = fields.TextField( _('Please specify other living situation'), [Optional(), validators.Length(max=32)] ) # How long have you lived in the greater Richmond area? # .time_living_in_area is parent node # years_living_in_area = fields.IntegerField(_("Years"), [Optional()]) # months_living_in_area = fields.IntegerField(_("Months"), [Optional()]) time_in_area = fields.SelectField( _('How long have you lived in the Greater Richmond area?'), choices=CONSTANTS.TIME_IN_AREA, default="" ) city_or_county_of_residence = fields.TextField( _('City or County of Residence'), [validators.Length(max=64)] ) temp_visa_yn = fields.SelectField( _("Are you traveling in the U.S. on a temporary Visa?"), choices=CONSTANTS.YN_CHOICES, default="", ) # has_transport_yn = db.Column(db.String(1), info='Has transportation?') # EMPLOYMENT # student_status = db.Column(db.String(16), info='Are you currently a student?') student_status = fields.SelectField( _('Student status'), choices=CONSTANTS.STUDENT_STATUS_CHOICES, default="", ) employment_status = fields.SelectField( _('Employment status'), choices=CONSTANTS.EMPLOYMENT_STATUS_CHOICES, default="", ) spouse_employment_status = fields.SelectField( _('Spouse\'s employment status'), choices=CONSTANTS.EMPLOYMENT_STATUS_CHOICES, default="", ) # How long have you been unemployed? # time_unemployed is the parent node years_unemployed = fields.IntegerField(_("Years"), [Optional()]) months_unemployed = fields.IntegerField(_("Months"), [Optional()]) # spouse_time_unemployed is the parent node spouse_years_unemployed = fields.IntegerField(_("Years"), [Optional()]) spouse_months_unemployed = fields.IntegerField(_("Months"), [Optional()]) # employment_changes # spouse_employment_changes employers = fields.FieldList(fields.FormField( EmployerForm )) years_at_current_employer = fields.SelectField( _('Years at current employer'), choices=CONSTANTS.TIME_AT_CURRENT_EMPLOYER, default="" ) spouse_years_at_current_employer = fields.SelectField( _('Spouse\'s years at current employer'), choices=CONSTANTS.TIME_AT_CURRENT_EMPLOYER, default="" ) # HEALTHCARE/COVERAGE last_healthcare = fields.TextField( _('When and where did you last receive healthcare services?'), [Optional(), validators.Length(max=128)] ) insurance_status = fields.SelectField( _('Do you have insurance or a card to help you cover medical costs?'), choices=CONSTANTS.YN_CHOICES, default="", ) coverage_type = fields.SelectField( _('Coverage type'), choices=CONSTANTS.COVERAGE_TYPE_CHOICES, default="", ) coverage_type_other = fields.TextField( _('Please specify other coverage type'), [Optional(), validators.Length(max=32)] ) has_prescription_coverage_yn = fields.SelectField( _('Do you have prescription drug coverage?'), choices=CONSTANTS.YNN_NONULL_CHOICES ) has_vcc = fields.SelectField( _("Do you have a VCC Card?"), choices=CONSTANTS.YN_CHOICES, default="" ) # has_pcp_yn # has_psychiatrist_yn # wants_psychiatrist_yn eligible_insurance_types = fields.SelectField( _('Are you eligible for insurance coverage through one of the following?'), choices=CONSTANTS.COVERAGE_ELIGIBILITY_CHOICES, default="" ) applied_for_vets_benefits_yn = fields.SelectField( _("Have you applied for veteran's benefits?"), choices=CONSTANTS.YNNA_CHOICES, default="" ) eligible_for_vets_benefits_yn = fields.SelectField( _("Are you eligible for veteran's benefits?"), choices=CONSTANTS.YNN_NONULL_CHOICES, default="" ) applied_for_medicaid_yn = fields.SelectField( _("Have you ever applied for Medicaid?"), choices=CONSTANTS.YN_CHOICES, default="" ) medicaid_date_effective = fields.DateField( _("Medicaid date effective"), [Optional()] ) applied_for_ssd_yn = fields.SelectField( _("Have you ever applied for Social Security Disability?"), choices=CONSTANTS.YN_CHOICES, default="" ) ssd_date_effective = fields.DateField( _("SSD date effective"), [Optional()], ) care_due_to_accident_yn = fields.SelectField( _("Is your healthcare the result of an accident?"), choices=CONSTANTS.YN_CHOICES, default="" ) accident_work_related_yn = fields.SelectField( _("Was the accident work-related?"), choices=CONSTANTS.YN_CHOICES, default="" ) # recently_lost_insurance_yn = fields.SelectField( # _("Have you lost your health benefits within the past year?"), # choices = CONSTANTS.YN_CHOICES, # default = "" # ) # INCOME/FINANCES document_images = fields.FieldList(fields.FormField( DocumentImageForm )) income_sources = fields.FieldList(fields.FormField( IncomeSourceForm )) household_members = fields.FieldList(fields.FormField( HouseholdMemberForm )) # head_of_household_yn filed_taxes_yn = fields.SelectField( _("Did you file taxes in the last year?"), choices=CONSTANTS.YN_CHOICES, default="" ) claimed_as_dependent_yn = fields.SelectField( _("Did someone else claim you on their return?"), choices=CONSTANTS.YNN_CHOICES, default="" ) how_food_and_shelter = fields.TextField( _('How do you provide food and shelter for yourself or your family?'), [Optional(), validators.Length(max=128)] ) how_other_expenses = fields.TextField( _('How do you provide for other daily living expenses, \ such as bills or medications, for yourself or your family?'), [Optional(), validators.Length(max=128)] )
class OpportunityForm(CategoryForm): '''Form to create and edit individual opportunities This form is an implementation of the CategoryForm, which means that it processes categories and subcategories in addition to the below fields. Attributes: department: link to :py:class:`~purchasing.users.models.Department` that is primarily responsible for administering the RFP, required opportunity_type: link to :py:class:`~purchasing.data.contracts.ContractType` objects that have the ``allow_opportunities`` field set to True contact_email: Email address of the opportunity's point of contact for questions title: Title of the opportunity, required description: 500 or less word description of the opportunity, required planned_publish: Date when the opportunity should be made public on Beacon planned_submission_start: Date when the opportunity opens to accept responses planned_submission_end: Date when the opportunity closes and no longer accepts submissions vendor_documents_needed: A multicheckbox for all documents that a vendor might need to respond to this opportunity. documents: A list of :py:class:`~purchasing.opportunities.forms.OpportunityDocumentForm` fields. See Also: * :py:class:`~purchasing.data.contracts.ContractType` The ContractType model informs the construction of the "How to Bid" section in the template * :py:class:`~purchasing.opportunities.models.Opportunity` The base model that powers the form. ''' department = QuerySelectField(query_factory=Department.query_factory, get_pk=lambda i: i.id, get_label=lambda i: i.name, allow_blank=True, blank_text='-----', validators=[DataRequired()]) opportunity_type = QuerySelectField( query_factory=ContractType.opportunity_type_query, get_pk=lambda i: i.id, get_label=lambda i: i.name, allow_blank=True, blank_text='-----', validators=[DataRequired()]) contact_email = fields.TextField( validators=[Email(), city_domain_email, DataRequired()]) title = fields.TextField(validators=[DataRequired()]) description = fields.TextAreaField( validators=[max_words(), DataRequired()]) planned_publish = fields.DateField(validators=[DataRequired()]) planned_submission_start = fields.DateField(validators=[DataRequired()]) planned_submission_end = DateTimeField( validators=[after_now, DataRequired()]) vendor_documents_needed = QuerySelectMultipleField( widget=select_multi_checkbox, query_factory=RequiredBidDocument.generate_choices, get_pk=lambda i: i[0], get_label=lambda i: i[1]) documents = fields.FieldList(fields.FormField(OpportunityDocumentForm), min_entries=1) def display_cleanup(self, opportunity=None): '''Cleans up data for display in the form 1. Builds the choices for the ``vendor_documents_needed`` 2. Formats the contact email for the form 3. Localizes the ``planned_submission_end`` time See Also: :py:meth:`CategoryForm.display_cleanup` Arguments: opportunity: A :py:class:`purchasing.opportunities.model.Opportunity` object or None. ''' self.vendor_documents_needed.choices = RequiredBidDocument.generate_choices( ) if opportunity and not self.contact_email.data: self.contact_email.data = opportunity.contact.email if self.planned_submission_end.data: self.planned_submission_end.data = pytz.UTC.localize( self.planned_submission_end.data).astimezone( current_app.config['DISPLAY_TIMEZONE']) super(OpportunityForm, self).display_cleanup() def data_cleanup(self): '''Cleans up form data for processing and storage 1. Pops off categories 2. Pops off documents (they are handled separately) 3. Sets the foreign keys Opportunity model relationships Returns: An ``opportunity_data`` dictionary, which can be used to instantiate or modify an :py:class:`~purchasing.opportunities.model.Opportunity` instance ''' opportunity_data = self.pop_categories(categories=False) opportunity_data.pop('documents') opportunity_data['department_id'] = self.department.data.id opportunity_data['contact_id'] = parse_contact( opportunity_data.pop('contact_email'), self.department.data) opportunity_data['vendor_documents_needed'] = [ int(i[0]) for i in opportunity_data['vendor_documents_needed'] ] return opportunity_data def process(self, formdata=None, obj=None, data=None, **kwargs): '''Processes category data and localizes ``planned_submission_end`` times See Also: :py:meth:`CategoryForm.process` ''' super(OpportunityForm, self).process(formdata, obj, data, **kwargs) if self.planned_submission_end.data and formdata: self.planned_submission_end.data = current_app.config[ 'DISPLAY_TIMEZONE'].localize( self.planned_submission_end.data).astimezone( pytz.UTC).replace(tzinfo=None)
class AnnouncementForm(Form): element_list = f.FieldList(f.FormField(AnnouncementElementForm)) result = f.TextAreaField('announcement')
class PIDselection(Form): PID = fields.FieldList(fields.TextField(('PID')), min_entries=3)
class recipeForm(form.Form): test_id = fields.IntegerField() recipe = fields.FieldList(fields.StringField()) version = fields.FieldList(fields.StringField())
class Query_list_form(form.Form): queries = fields.FieldList(FormField(query_form, default=lambda: query_data()), min_entries=0) query1 = StringField(label='Query') submit_query = SubmitField(label='Save')
class CommandNamesForm(Form): items = f.FieldList(f.FormField(CommandNameForm))