class AddPlantForm(Form): pname = StringField(' Plant Name', [ validators.Length(min=4, max=25), validators.DataRequired(), ]) fertilizer = StringField('Fertilizer', [ validators.Length(min=4, max=25), validators.DataRequired(), ]) weather = SelectField('Weather', choices=[('summer', 'Summer'), ('winter', 'Winter'), ('all_season', 'All Season')]) sunlight = SelectField('Sunlight', choices=[('mild', 'Mild'), ('moderate', 'Moderate'), ('extreme', 'Extreme')]) potsize = SelectField('Pot Size', choices=[('small', 'Small'), ('medium', 'Medium'), ('large', 'Large')]) water = IntegerField("Water Requirement (in ml)") special = TextField('Special Requirements', [ validators.Length(min=4, max=100), ]) uses = SelectMultipleField("Uses", choices=[("cosmetic", "Cosmetic"), ("medicinal", "Medicinal"), ("decorative", "Decorative"), ("edible", "Edible")])
class TransactionForm(Form): """Transaction form.""" type = SelectField( 'Transaction Type', choices=[('expense', 'Expense'), ('Income', 'Income')] ) account = SelectField( 'Account', choices=[('Stratos Cash', 'Stratos Cash'), ('Arzu Cash', 'Arzu Cash'), ('text', 'Plain Text')] ) amount = DecimalField('Amount', places=2, validators=[DataRequired(), ]) # The date format has to mimic the moment.js format set in: # templates/transactions/new.html trx_date = DateTimeField('Transaction Date', format="%A, %B %d %Y, %H:%M") def __init__(self, *args, **kwargs): """Create instance.""" super(TransactionForm, self).__init__(*args, **kwargs) def validate(self): """Validate the form.""" initial_validation = super(TransactionForm, self).validate() if not initial_validation: return False return True
class VCRoomLinkFormBase(IndicoForm): conditional_fields = {'contribution', 'block'} linking = IndicoRadioField(_("Link to"), [DataRequired()], choices=[('event', _("Event")), ('contribution', _("Contribution")), ('block', _("Session"))], widget=LinkingWidget()) contribution = SelectField(_("Contribution"), [UsedIf(lambda form, field: form.linking.data == 'contribution'), DataRequired()], coerce=lambda x: int(x) if x else None) block = SelectField(_("Session block"), [UsedIf(lambda form, field: form.linking.data == 'block'), DataRequired()], coerce=lambda x: int(x) if x else None) show = BooleanField(_('Show room'), widget=SwitchWidget(), description=_('Display this room on the event page')) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) contrib_choices = [(contrib.id, contrib.title) for contrib in sorted(self.event.contributions, key=attrgetter('title'))] blocks = SessionBlock.find(SessionBlock.session.has((Session.event == self.event) & ~Session.is_deleted)) block_choices = [(block.id, block.full_title) for block in sorted(blocks, key=attrgetter('full_title'))] self.contribution.choices = [('', _("Please select a contribution"))] + contrib_choices self.block.choices = [('', _("Please select a session block"))] + block_choices
class VCRoomLinkFormBase(IndicoForm): conditional_fields = {'contribution', 'block'} linking = IndicoRadioField(_("Link to"), [DataRequired()], choices=[('event', _("Event")), ('contribution', _("Contribution")), ('block', _("Session"))], widget=LinkingWidget()) contribution = SelectField(_("Contribution"), [ UsedIf(lambda form, field: form.linking.data == 'contribution'), DataRequired() ]) block = SelectField(_("Session block"), [ UsedIf(lambda form, field: form.linking.data == 'block'), DataRequired() ]) show = BooleanField(_('Show room'), widget=SwitchWidget(), description=_('Display this room on the event page')) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super(VCRoomLinkFormBase, self).__init__(*args, **kwargs) contrib_choices = [(contrib.id, contrib.title) for contrib in sorted( self.event.getContributionList(), key=attrgetter('title'))] block_choices = [(full_block_id(block), block.getFullTitle()) for block in sorted(self.event.getSessionSlotList(), key=methodcaller('getFullTitle'))] self.contribution.choices = [('', _("Please select a contribution")) ] + contrib_choices self.block.choices = [('', _("Please select a session block")) ] + block_choices
class DocPresc(FlaskForm): order_date = StringField("What day was it prescribed?", validators=[Required(), Regexp('^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$', 0, 'Date must be in YYYY-MM-DD format')]) pat_id = SelectField("What is the patient's id", validators=[Required()], choices= ["P56544020", "P71774482"]) m_id = SelectField("What is the medicine id", validators=[Required()], choices=["M1135", "M1472", "M1476", "M2559"]) pc_id = SelectField("What is the pharmacy id", validators=[Required()], choices = ["PC165750", "PC301085"]) order_quant = StringField("How many are being prescribed", validators=[Required()]) submit = SubmitField("Submit Registration")
class FakeSearchForm(SearchForm): collection = SelectField(_('Search for'), choices=COLLECTION_CHOICES, default='') sort_order = SelectField(_('Sort order'), choices=SORT_ORDER_CHOICES, default='d')
class PharmacySearch(FlaskForm): search = StringField("search by medicine name here") #change to query to populate the pharmacy dropdown plant = SelectField("select a pharmacy plant to shop from", choices=["PP200053", "PP323961"]) sortby = SelectField("sort by", choices=["unit_price", "stock_quant"]) order = SelectField("order", choices = ["ascending","descending"]) submit = SubmitField("Search")
class UserPreferencesForm(IndicoForm): lang = SelectField(_('Language')) timezone = SelectField(_('Timezone')) force_timezone = BooleanField( _('Use my timezone'), widget=SwitchWidget(), description=_( "Always use my current timezone instead of an event's timezone.")) show_past_events = BooleanField( _('Show past events'), widget=SwitchWidget(), description=_('Show past events by default.')) name_format = IndicoEnumSelectField( _('Name format'), enum=NameFormat, description=_('Default format in which names are displayed')) use_previewer_pdf = BooleanField( _('Use previewer for PDF files'), widget=SwitchWidget(), description= _('The previewer is used by default for image and text files, but not for PDF files.' )) def __init__(self, *args, **kwargs): super(UserPreferencesForm, self).__init__(*args, **kwargs) self.lang.choices = sorted(get_all_locales().items(), key=itemgetter(1)) self.timezone.choices = zip(all_timezones, all_timezones)
class FormNoticia(FlaskForm): id = HiddenField(validators=[Optional()]) categoria = SelectField( "Categoria", choices=[ ("Geral", "Geral"), ("Segurança", "Segurança"), ("Saúde", "Saúde"), ("Economia", "Economia"), ], default="Geral", ) titulo = StringField( "Título", [ DataRequired(message="Informe título da notícia."), Length(5, 150, message="Deve ter pelo menos 5 caracteres."), ], ) conteudo = TextAreaField("Conteúdo") destaque = SelectField( "Destacar na página inicial?", choices=[("sim", "Sim"), ("nao", "Não")], default="nao", ) thumb = FileField("Imagem de capa da notícia", validators=[Optional()])
class ProductForm(FlaskForm): productName = StringField('Product Name', validators=[DataRequired()]) slug = StringField('Slug', validators=[DataRequired()]) price = IntegerField('Price', validators=[DataRequired()]) discount = IntegerField('Discount') stock = IntegerField('Stock', validators=[DataRequired()]) category = SelectField('Category', choices=[], validators=[DataRequired()]) brand = SelectField('Brand', choices=[]) color = StringField('Color') size = StringField('Size') weight = StringField('Weight') dimension = StringField('Dimension') material = StringField('Material') shortDescription = TextAreaField('Short Description') longDescription = TextAreaField('Long Description') imageFile = FileField('Set Featured image', validators=[FileAllowed(['jpg', 'png'])]) imageGallery = FileField('Gallery', validators=[FileAllowed(['jpg', 'png'])]) featured = BooleanField("Featured") # product_user_id = current_user submit = SubmitField('Add Product') edit = SubmitField('Save Changes')
class CafeForm(FlaskForm): cafe = StringField('Cafe name', validators=[DataRequired()]) location =StringField('Cafe Location on Google Maps (URL)', validators=[DataRequired(), validators.URL()]) openTime = StringField('Opening Time e.g. 8AM', validators=[DataRequired()]) closeTime = StringField('Closing time e.g. 5:30PM', validators=[DataRequired()]) coffeeRate = SelectField('Coffee Rating', choices=cRating) wifiRate = SelectField('Wifi Strength Rating', choices=wRaiting) socketNum = SelectField('Power Socket Availability', choices=sRating) submit = SubmitField('Submit')
class ExportForm(FlaskForm): export_type = SelectField(_("What do you want to download ?"), validators=[Required()], coerce=str, choices=[("bills", _("bills")), ("transactions", _("transactions"))]) export_format = SelectField(_("Export file format"), validators=[Required()], coerce=str, choices=[("csv", "csv"), ("json", "json")])
class FormRule(DefaultForm): route = TextField(localize("administration", "rules.field_route"), validators=[DataRequired()]) role_id = SelectField(localize("administration", "rules.field_role"), coerce=int) insert = SelectField(localize("administration", "rules.field_insert"), choices=[(item, item) for item in Rule.permissions]) remove = SelectField(localize("administration", "rules.field_remove"), choices=[(item, item) for item in Rule.permissions]) change = SelectField(localize("administration", "rules.field_change"), choices=[(item, item) for item in Rule.permissions]) view = SelectField(localize("administration", "rules.field_view"), choices=[(item, item) for item in Rule.permissions])
class RegistrationPatientForm(FlaskForm): username = StringField('User Name', validators=[Required(), Length(1,20), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0,'usernames must have only letters, ''numbers, dots or underscores')]) password = PasswordField('Password', validators=[Required(), EqualTo('password2', message = "Passwords must be identical")]) password2 = PasswordField('Confirm Password', validators=[Required()]) doc_id = SelectField('Doctor id', validators=[Required()], choices=["DT1013066794", "DT1003914227"]) first_name = StringField('Patient First Name', validators=[Required()]) last_name = StringField('Patient Last Name', validators=[Required()]) gender = SelectField("Patient Gender", validators=[Required()], choices = ["M", "F"]) ethnicity = SelectField("Patient ethnicity", validators=[Required()], choices= ["American Indian or Alaska Native", "Asian", "Black or African American", "Hispanic or Latino", "Native Hawaiian or Other Pacific Islander", "White"]) dob = StringField("Patient date of birth", validators=[Required(), Regexp('^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$', 0, 'Date must be in YYYY-MM-DD format')]) email_address = StringField('Patient Email Address', validators=[Required(), Regexp('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', 0, 'must be a valid email address')]) phone_number = StringField('Patient Phone Number', validators=[Required(), Regexp('[2-9]\d{2}-\d{3}-\d{4}$', 0, "must be a valid phone-number (###-###-####)") ]) submit = SubmitField("Submit Registration")
class BookForm(FlaskForm): name = StringField(label="Book Name", validators=[DataRequired()]) author = StringField(label="Book Author", validators=[DataRequired()]) rating = SelectField(label="Rating", validators=[DataRequired()], choices=[1, 2, 3, 4, 5]) submit = SubmitField("submit")
class BusinessForm(AfterLoginForm): name = StringField("Name", validators=[ InputRequired(), Length(2, 15, "Name does not respect our rules.") ]) description = StringField("Description", widget=TextArea()) fiscal_number = StringField( "Fiscal number", validators=[InputRequired(), Length(8, 15, "Tax number isn't valid.")]) phone = StringField("Phone", validators=[ InputRequired(), Length(6, 20, "Phone number isn't valid.") ]) mobile = StringField("Mobile", validators=[ InputRequired(), Length(6, 20, "Mobile number isn't valid.") ]) def get_areas(): query = db.execute("SELECT id, designation FROM businessAreas") sectors = list() for value in query: sectors.append((value["id"], value["designation"])) return sectors activity_sector = SelectField("Sector", choices=get_areas())
class VCRoomListFilterForm(IndicoForm): direction = SelectField(_('Sort direction'), [DataRequired()], choices=[('asc', _('Ascending')), ('desc', _('Descending'))]) abs_start_date = IndicoDateField( _('Start Date'), [Optional(), Exclusive('rel_start_date')]) abs_end_date = IndicoDateField( _('End Date'), [Optional(), Exclusive('rel_end_date')]) rel_start_date = IntegerField( _('Days in the past'), [Optional(), Exclusive('abs_start_date'), NumberRange(min=0)], default=0) rel_end_date = IntegerField( _('Days in the future'), [Optional(), Exclusive('abs_end_date'), NumberRange(min=0)], default=7) @generated_data def start_date(self): if self.abs_start_date.data is None and self.rel_start_date.data is None: return None return self.abs_start_date.data or ( date.today() - timedelta(days=self.rel_start_date.data)) @generated_data def end_date(self): if self.abs_end_date.data is None and self.rel_end_date.data is None: return None return self.abs_end_date.data or ( date.today() + timedelta(days=self.rel_end_date.data))
class OutlookUserPreferences(ExtraUserPreferences): fields = { 'outlook_active': BooleanField( _('Sync with Outlook'), widget=SwitchWidget(), description=_( 'Add Indico events in which I participate to my Outlook ' 'calendar')), 'outlook_status': SelectField(_('Outlook entry status'), [HiddenUnless('extra_outlook_active', preserve_data=True)], choices=_status_choices, description=_('The status for Outlook Calendar entries')) } def load(self): default_status = OutlookPlugin.settings.get('status') return { 'outlook_active': OutlookPlugin.user_settings.get(self.user, 'enabled'), 'outlook_status': OutlookPlugin.user_settings.get(self.user, 'status', default_status) } def save(self, data): OutlookPlugin.user_settings.set_multi(self.user, { 'enabled': data['outlook_active'], 'status': data['outlook_status'] })
class RunForm(FlaskForm): id_org = SelectField('Organization', [DataRequired()], choices=[("actc", "ACTC"), ("apat", "APAT"), ("aptp", "APTP"), ( "auvo", "AUVO"), ("carx", "CARX"), ("cur", "CUR"), ("gpu", "GPU"), ("mss", "MSS"), ("tc", "TC"), ("tr", "TR")]) year = IntegerField('Year') manual = BooleanField('Manual') org = HiddenField('org') submit = SubmitField('create')
class AdminSettingsForm(fossirForm): currencies = MultipleItemsField( _('Currencies'), [DataRequired()], fields=[{ 'id': 'code', 'caption': _('Code') }, { 'id': 'name', 'caption': _('Name') }], unique_field='code', description= _("List of currencies that can be selected for an event. When deleting " "a currency, existing events will keep using it. The currency code " "must be a valid <a href='{0}'>ISO-4217</a> code such " "as 'EUR' or 'CHF'.").format(CURRENCY_CODE_LINK)) currency = SelectField( _('Currency'), [DataRequired()], description=_( 'The default currency for new events. If you add a new currency, you need to ' 'save the settings first for it to show up here.')) conditions = TextAreaField(_('Conditions'), description=CONDITIONS_DESC) def __init__(self, *args, **kwargs): super(AdminSettingsForm, self).__init__(*args, **kwargs) self._set_currencies() def _set_currencies(self): currencies = [(c['code'], '{0[code]} ({0[name]})'.format(c)) for c in payment_settings.get('currencies')] self.currency.choices = sorted(currencies, key=lambda x: x[1].lower()) def validate_currency(self, field): if field.data not in {c['code'] for c in self.currencies.data}: raise ValidationError('Please select a different currency.')
class AppointmentForm(FlaskForm): available_drs = [(doc.id, doc.username) for doc in User.query.filter_by(role='doctor')] doctor_id = SelectField('Doctor', choices=available_drs, validators=[DataRequired()]) appointment_time = DateTimeLocalField('Time', format='%Y-%m-%dT%H:%M', validators=[DataRequired()]) # appointment_time = DateTimeField('Time', validators=[DataRequired()]) submit = SubmitField('Reserve') def validate_appointment_time(self, appointment_time): # check if dr is available at that time # query appointment for any for the current doctor appointment_time = appointment_time.data reserved = Appointment.query.filter_by( doctor_id=int(self.doctor_id.data)).filter( Appointment.datetime.between( appointment_time - timedelta(minutes=29), appointment_time + timedelta(minutes=29))).first() if reserved: dr = User.query.get(int(self.doctor_id.data)) raise ValidationError( f'Dr {dr.username} is not available at that time. Please choose a different one.' )
class BillForm(FlaskForm): date = DateField(_("Date"), validators=[Required()], default=datetime.now) what = StringField(_("What?"), validators=[Required()]) payer = SelectField(_("Payer"), validators=[Required()], coerce=int) amount = CommaDecimalField(_("Amount paid"), validators=[Required()]) payed_for = SelectMultipleField(_("For whom?"), validators=[Required()], coerce=int) submit = SubmitField(_("Submit")) submit2 = SubmitField(_("Submit and add a new one")) def save(self, bill, project): bill.payer_id = self.payer.data bill.amount = self.amount.data bill.what = self.what.data bill.date = self.date.data bill.owers = [ Person.query.get(ower, project) for ower in self.payed_for.data ] return bill def fill(self, bill): self.payer.data = bill.payer_id self.amount.data = bill.amount self.what.data = bill.what self.date.data = bill.date self.payed_for.data = [int(ower.id) for ower in bill.owers] def set_default(self): self.payed_for.data = self.payed_for.default def validate_amount(self, field): if field.data == 0: raise ValidationError(_("Bills can't be null"))
class DUpdateAccountForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)]) email = StringField('Email', validators=[DataRequired(), Email()]) picture = FileField('Update Profile Picture', validators=[FileAllowed(['jpg', 'png'])]) mobile_number = StringField('Mobile Number', validators=[DataRequired()]) gender = SelectField('Gender', choices=[('male', 'male'), ('female', 'female')], validators=[DataRequired()]) age = IntegerField('Age', validators=[DataRequired()]) national_id = StringField('National ID Number', validators=[DataRequired(), Length(14)]) submit = SubmitField('Update') def validate_username(self, username): if username.data != current_user.username: user = User.query.filter_by(username=username.data).first() if user: raise ValidationError( 'That username is taken. Please choose a different one.') def validate_email(self, email): if email.data != current_user.email: user = User.query.filter_by(email=email.data).first() if user: raise ValidationError( 'That email is taken. Please choose a different one.')
class BookForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) author = StringField('Author', validators=[DataRequired()]) rating = SelectField("Rating", choices=[1, 2, 3, 4, 5], validators=[DataRequired()]) add = SubmitField("Add")
class SearchForm(IndicoForm): phrase = StringField(_('Phrase')) field = SelectField(_('Search in'), choices=FIELD_CHOICES, default='') start_date = DateField('Start Date', [Optional()], parse_kwargs={'dayfirst': True}) end_date = DateField('End Date', [Optional()], parse_kwargs={'dayfirst': True})
class NewUserForm(SimpleForm): gmbh_name = StringField(label='Name der GmbH') sitz = StringField(label='Sitz') # notariat = StringField() # anrede_bevollmaechtigter = SelectField(choices=(('Herr', 'Herr'), ('Frau', 'Frau'))) # vorname_bevollmaechtigter = StringField() # nachname_bevollmaechtigter = StringField() # geburtstag_bevollmaechtigter = DateField(format='%d.%m.%Y') # buergerort_bevollmaechtigter = StringField() # wohnort_bevollmaechtigter = StringField() anrede_gruender = SelectField(label='Anrede', choices=(('Herr', 'Herr'), ('Frau', 'Frau'))) vorname_gruender = StringField(label='Vorname') nachname_gruender = StringField(label='Nachname') telefon_gruender = StringField(label='Telefon') email_gruender = EmailField(label='Email') geburtstag_gruender = DateField(label='Geburtsdatum', format='%d.%m.%Y') buergerort_gruender = StringField(label='Bürgerort') strasse_gruender = StringField(label='Adresse') wohnort_gruender = StringField(label='Postleitzahl und Ort') datum_gruendung = DateField(label='Gewünschtes Gründungsdatum', format='%d.%m.%Y') # bank = StringField() branche_taetigkeit = StringField(label='Branche/Tätigkeit') zweck = StringField(label='Zweck')
class TimestampForm(FlaskForm): date = DateField("DatePicker", format="%Y-%m-%d") time = TimeField("TimePicker", format="%H:%M") time_zone = SelectField( "TimeZonePicker", choices=tuple(zip(pendulum.timezones, pendulum.timezones)), )
class VCRoomLinkFormBase(IndicoForm): conditional_fields = {'contribution', 'block'} linking = IndicoRadioField(_("Link to"), [DataRequired()], choices=[('event', _("Event")), ('contribution', _("Contribution")), ('block', _("Session"))], widget=LinkingWidget()) contribution = SelectField(_("Contribution"), [ UsedIf(lambda form, field: form.linking.data == 'contribution'), DataRequired() ], coerce=lambda x: int(x) if x else None) block = SelectField(_("Session block"), [ UsedIf(lambda form, field: form.linking.data == 'block'), DataRequired() ], coerce=lambda x: int(x) if x else None) show = BooleanField(_('Show room'), widget=SwitchWidget(), description=_('Display this room on the event page')) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') super().__init__(*args, **kwargs) contrib_choices = [ (contrib.id, '{} (#{}, {})'.format( contrib.title, contrib.friendly_id, format_datetime(contrib.start_dt, timezone=self.event.tzinfo))) for contrib in sorted(self.event.contributions, key=lambda c: (c.title, c.start_dt or as_utc( datetime(1970, 1, 1)))) if contrib.start_dt is not None ] blocks = (SessionBlock.query.filter( SessionBlock.session.has((Session.event == self.event) & ~Session.is_deleted)).all()) block_choices = [(block.id, '{} ({})'.format( block.full_title, format_datetime(block.start_dt, timezone=self.event.tzinfo))) for block in sorted( blocks, key=attrgetter('full_title', 'start_dt'))] self.contribution.choices = [('', _("Please select a contribution")) ] + contrib_choices self.block.choices = [('', _("Please select a session block")) ] + block_choices
class EditProjectForm(FlaskForm): name = StringField(_("Project name"), validators=[DataRequired()]) password = StringField(_("Private code"), validators=[DataRequired()]) contact_email = StringField(_("Email"), validators=[DataRequired(), Email()]) project_history = BooleanField(_("Enable project history")) ip_recording = BooleanField(_("Use IP tracking for project history")) currency_helper = CurrencyConverter() default_currency = SelectField(_("Default Currency"), validators=[DataRequired()]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.default_currency.choices = [ (currency_name, render_localized_currency(currency_name, detailed=True)) for currency_name in self.currency_helper.get_currencies() ] @property def logging_preference(self): """Get the LoggingMode object corresponding to current form data.""" if not self.project_history.data: return LoggingMode.DISABLED else: if self.ip_recording.data: return LoggingMode.RECORD_IP else: return LoggingMode.ENABLED def save(self): """Create a new project with the information given by this form. Returns the created instance """ project = Project( name=self.name.data, id=self.id.data, password=generate_password_hash(self.password.data), contact_email=self.contact_email.data, logging_preference=self.logging_preference, default_currency=self.default_currency.data, ) return project def update(self, project): """Update the project with the information from the form""" project.name = self.name.data # Only update password if changed to prevent spurious log entries if not check_password_hash(project.password, self.password.data): project.password = generate_password_hash(self.password.data) project.contact_email = self.contact_email.data project.logging_preference = self.logging_preference project.default_currency = self.default_currency.data return project
class UserPreferencesForm(IndicoForm): lang = SelectField(_('Language')) timezone = SelectField(_('Timezone')) force_timezone = BooleanField( _('Use my timezone'), widget=SwitchWidget(), description= 'Always use my current timezone instead of an event\'s timezone.') show_past_events = BooleanField(_('Show past events'), widget=SwitchWidget(), description='Show past events by default.') def __init__(self, *args, **kwargs): super(UserPreferencesForm, self).__init__(*args, **kwargs) self.lang.choices = sorted(get_all_locales().items(), key=itemgetter(1)) self.timezone.choices = zip(all_timezones, all_timezones)