def _set_fields(self, form): setattr(form, 'brand_name', TextField('Brand Name (lowercase)')) setattr(form, 'brand_name_case', TextField('Brand Name (proper case)')) setattr(form, 'css_file', TextField('CSS File')) setattr(form, 'index_file', TextField('Index File')) setattr(form, 'categories_json', TextAreaField('Categories (JSON string)', validators=[custom_validators.JSONValidator()])) setattr(form, 'specialties_display', BooleanField('Display Specialties')) setattr(form, 'specialties_json', TextAreaField('Specialties (JSON string)', validators=[custom_validators.JSONValidator()])) setattr(form, 'associations_json', TextAreaField('Associations (JSON string)', validators=[custom_validators.JSONValidator()])) setattr(form, 'certifications_display', BooleanField('Display Certifications')) setattr(form, 'certifications_json', TextAreaField('Certifications (JSON string)', validators=[custom_validators.JSONValidator()]))
class JobForm (Form): """ Form for creating new Job """ name = StringField ('name', validators=[DataRequired ()]) script = TextAreaField ('script', validators=[DataRequired ()]) def validate (self): result = super (Form, self).validate () if not result: return result if db.jobs.search_one ({ 'name': self.name.data }) is not None: self.username.errors.append ('Job with this name already exists') return False # create job instance and default script instance job = JobManagementApplication.create (user_id=current_user.user.id, name=self.name.data) script = ScriptManagementApplication.create (job_id=job.id, commandsNew=self.script.data) # add default instance id to jobs scripts list job.add_script (script) # add script and job to db db.scripts.add (script) db.jobs.add (job) #commit changes transaction.commit () return True
class MailtoolForm(Form): recipients = HiddenField() subject = StringField("Subject", render_kw={"placeholder": "Enter the email subject"}) replyto = StringField( "Reply-To", render_kw={"placeholder": "Enter an alternative reply-to address (optional)"}) dryrun = BooleanField("Dry-run") body = TextAreaField("Body", render_kw=_taf)
class PluginSettingsForm(PaymentPluginSettingsFormBase): details = TextAreaField(_('Payment details'), []) def __init__(self, *args, **kwargs): super(PluginSettingsForm, self).__init__(*args, **kwargs) self.details.description = DETAILS_DESC + '\n' + render_placeholder_info( 'manual-payment-details', regform=None, registration=None)
class AdminSettingsForm(IndicoForm): currencies = MultipleItemsField( _('Currencies'), [DataRequired()], fields=(('code', _('Code')), ('name', _('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) checkout_session_timeout = IntegerField( 'Checkout session timeout', validators=[DataRequired(), NumberRange(min=0)], description=CHECKOUT_SESSION_TIMEOUT_MSG) 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 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 EventSettingsForm(PaymentEventSettingsFormBase): details = TextAreaField(_('Payment details'), [UsedIf(lambda form, _: form.enabled.data), DataRequired()]) def __init__(self, *args, **kwargs): super(EventSettingsForm, self).__init__(*args, **kwargs) self.details.description = DETAILS_DESC + '\n' + render_placeholder_info('manual-payment-details', regform=None, registration=None)
class VCRoomForm(VCRoomFormBase, ZoomAdvancedFormMixin): """Contains all information concerning a Zoom booking""" advanced_fields = {'show_autojoin', 'show_phone_numbers' } | VCRoomFormBase.advanced_fields skip_fields = advanced_fields | VCRoomFormBase.conditional_fields description = TextAreaField(_('Description'), [DataRequired()], description=_('The description of the room')) #owner_user = PrincipalField(_('Owner'), [DataRequired()], description=_('The owner of the room')) #owner_user = HiddenField(default=session.user) #moderation_pin = IndicoPasswordField(_('Moderation PIN'), PIN_VALIDATORS, toggle=True, # description=_('Used to moderate the VC Room. Only digits allowed.')) #room_pin = IndicoPasswordField(_('Room PIN'), PIN_VALIDATORS, toggle=True, # description=_('Used to protect the access to the VC Room (leave blank for open ' # 'access). Only digits allowed.')) def __init__(self, *args, **kwargs): defaults = kwargs['obj'] if defaults.owner_user is None and defaults.owner is not None: defaults.owner_user = retrieve_principal(defaults.owner) super(VCRoomForm, self).__init__(*args, **kwargs) #@generated_data #def owner(self): # return self.owner_user.data.default def validate_owner_user(self, field): if not field.data: raise ValidationError(_("Unable to find this user in Indico."))
class ArtForm(FlaskForm): artist = StringField('Artist', validators=[DataRequired()]) title = StringField('Title', validators=[DataRequired()]) description = TextAreaField('Description', filters=[lambda x: x or None]) source = StringField('Source', validators=[DataRequired()]) submit = SubmitField('Submit') delete = SubmitField('Delete')
class PostForm(FlaskForm): title = StringField('Title', validators=[DataRequired()]) body = TextAreaField('Body', validators=[DataRequired(), Length(max=1500)]) happiness_level = SelectField('Happiness Level', choices=[(3, 'I can\'t stop smiling'), (2, 'Really happy'), (1, 'Happy')]) submit = SubmitField('Post')
class textForm(FlaskForm): text = TextAreaField('Enter Text', validators=[DataRequired(), Length(min=1)], widget=TextArea()) submit = SubmitField('Predict')
class NewBookingConfirmForm(NewBookingPeriodForm): booked_for_user = PrincipalField(_(u'User'), [DataRequired()], allow_external=True) contact_email = StringField( _(u'Email'), [InputRequired(), IndicoEmail(multi=True)]) contact_phone = StringField(_(u'Telephone')) booking_reason = TextAreaField(_(u'Reason'), [DataRequired()]) uses_vc = BooleanField(_(u'I will use videoconference equipment')) used_equipment = IndicoQuerySelectMultipleCheckboxField( _(u'VC equipment'), get_label=lambda x: x.name) needs_vc_assistance = BooleanField( _(u'Request assistance for the startup of the videoconference session. ' u'This support is usually performed remotely.')) needs_assistance = BooleanField( _(u'Request personal assistance for meeting startup')) submit_book = SubmitField(_(u'Create booking')) submit_prebook = SubmitField(_(u'Create pre-booking')) def validate_used_equipment(self, field): if field.data and not self.uses_vc.data: raise ValidationError(_(u'Videoconference equipment is not used.')) elif not field.data and self.uses_vc.data: raise ValidationError( _(u'You need to select some Videoconference equipment')) def validate_needs_vc_assistance(self, field): if field.data and not self.uses_vc.data: raise ValidationError(_(u'Videoconference equipment is not used.'))
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 AdminSettingsForm(IndicoForm): 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().__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 UploadForm(FlaskForm): description = TextAreaField('Description', validators=[InputRequired()]) photo = FileField('Photo', validators=[ FileRequired(), FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!') ])
class ContactForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) subject = StringField('Subject', validators=[DataRequired(), Length(min=2, max=20)]) content = TextAreaField('Text') submit = SubmitField('Send')
class NewBookingConfirmForm(NewBookingPeriodForm): room_usage = RadioField( [DataRequired()], choices=[('current_user', _("I'll be using the room myself")), ('other_user', _("I'm booking the room for someone else"))]) booked_for_user = PrincipalField( _('User'), [HiddenUnless('room_usage', 'other_user'), DataRequired()], allow_external=True) booking_reason = TextAreaField(_('Reason'), [DataRequired()]) uses_vc = BooleanField(_('I will use videoconference equipment')) used_equipment = IndicoQuerySelectMultipleCheckboxField( _('VC equipment'), get_label=lambda x: x.name) needs_vc_assistance = BooleanField( _('Request assistance for the startup of the videoconference session. ' 'This support is usually performed remotely.')) needs_assistance = BooleanField( _('Request personal assistance for meeting startup')) submit_book = SubmitField(_('Create booking')) submit_prebook = SubmitField(_('Create pre-booking')) def validate_used_equipment(self, field): if field.data and not self.uses_vc.data: raise ValidationError(_('Videoconference equipment is not used.')) elif not field.data and self.uses_vc.data: raise ValidationError( _('Please select the type of videoconference that you will use.' )) def validate_needs_vc_assistance(self, field): if field.data and not self.uses_vc.data: raise ValidationError(_('Videoconference equipment is not used.'))
class RoomForm(IndicoForm): name = StringField(_(u'Name')) site = StringField(_(u'Site')) building = StringField(_(u'Building'), [DataRequired()]) floor = StringField(_(u'Floor'), [DataRequired()]) number = StringField(_(u'Number'), [DataRequired()]) longitude = FloatField(_(u'Longitude'), [Optional()]) latitude = FloatField(_(u'Latitude'), [Optional()]) is_active = BooleanField(_(u'Active'), default=True) is_reservable = BooleanField(_(u'Public'), default=True) reservations_need_confirmation = BooleanField(_(u'Confirmations')) notification_for_assistance = BooleanField(_(u'Assistance')) notification_before_days = IntegerField(_(u'Send booking reminders X days before (single/daily)'), [Optional(), NumberRange(min=1, max=30)]) notification_before_days_weekly = IntegerField(_(u'Send booking reminders X days before (weekly)'), [Optional(), NumberRange(min=1, max=30)]) notification_before_days_monthly = IntegerField(_(u'Send booking reminders X days before (monthly)'), [Optional(), NumberRange(min=1, max=30)]) notifications_enabled = BooleanField(_(u'Reminders enabled'), default=True) booking_limit_days = IntegerField(_(u'Maximum length of booking (days)'), [Optional(), NumberRange(min=1)]) owner = PrincipalField(_(u'Owner'), [DataRequired()], allow_external=True) key_location = StringField(_(u'Where is key?')) telephone = StringField(_(u'Telephone')) capacity = IntegerField(_(u'Capacity'), [Optional(), NumberRange(min=1)], default=20) division = StringField(_(u'Department')) surface_area = IntegerField(_(u'Surface area'), [Optional(), NumberRange(min=0)]) max_advance_days = IntegerField(_(u'Maximum advance time for bookings'), [Optional(), NumberRange(min=1)]) comments = TextAreaField(_(u'Comments')) delete_photos = BooleanField(_(u'Delete photos')) large_photo = FileField(_(u'Large photo')) available_equipment = IndicoQuerySelectMultipleCheckboxField(_(u'Equipment'), get_label=_get_equipment_label, modify_object_list=_group_equipment) # attribute_* - set at runtime bookable_hours = FieldList(FormField(_TimePair), min_entries=1) nonbookable_periods = FieldList(FormField(_DateTimePair), min_entries=1)
class NewPostForm(Form): id = HiddenField() title = TextField('Title', validators=[Length(min=3, max=500)]) text = TextAreaField('Text', validators=[Required(), ]) url = URLField('URL') image_url = URLField('Image URL') publish_date = DateTimeField("Publish at date", default=datetime.datetime.now())
class UserDetailsForm(SyncedInputsMixin, IndicoForm): title = IndicoEnumSelectField(_('Title'), enum=UserTitle) first_name = StringField(_('First name'), [used_if_not_synced, DataRequired()], widget=SyncedInputWidget()) last_name = StringField(_('Family name'), [used_if_not_synced, DataRequired()], widget=SyncedInputWidget()) affiliation = StringField(_('Affiliation'), widget=SyncedInputWidget()) address = TextAreaField(_('Address'), widget=SyncedInputWidget(textarea=True)) phone = StringField(_('Phone number'), widget=SyncedInputWidget())
class VCRoomForm(VCRoomFormBase, VidyoAdvancedFormMixin): """Contains all information concerning a Vidyo booking""" advanced_fields = {'show_pin', 'show_autojoin', 'show_phone_numbers'} | VCRoomFormBase.advanced_fields skip_fields = advanced_fields | VCRoomFormBase.conditional_fields description = TextAreaField(_('Description'), [DataRequired()], description=_('The description of the room')) owner_user = PrincipalField(_('Owner'), [DataRequired()], description=_('The owner of the room')) moderation_pin = IndicoPasswordField(_('Moderation PIN'), PIN_VALIDATORS, toggle=True, description=_('Used to moderate the VC Room. Only digits allowed.')) room_pin = IndicoPasswordField(_('Room PIN'), PIN_VALIDATORS, toggle=True, description=_('Used to protect the access to the VC Room (leave blank for open ' 'access). Only digits allowed.')) auto_mute = BooleanField(_('Auto mute'), widget=SwitchWidget(_('On'), _('Off')), description=_('The VidyoDesktop clients will join the VC room muted by default ' '(audio and video)')) def __init__(self, *args, **kwargs): defaults = kwargs['obj'] if defaults.owner_user is None and defaults.owner is not None: defaults.owner_user = retrieve_principal(defaults.owner) super(VCRoomForm, self).__init__(*args, **kwargs) @generated_data def owner(self): return self.owner_user.data.as_principal def validate_owner_user(self, field): if not field.data: raise ValidationError(_("Unable to find this user in Indico.")) if not next(iter_user_identities(field.data), None): raise ValidationError(_("This user does not have a suitable account to use Vidyo."))
class MessageForm(Form): digest = TextField( "Pyzor digest*", validators=[length(40, 40, "Invalid Digest"), required()]) message = FileField('Raw message*') name = TextField('Name') email = EmailField('Email') comment = TextAreaField('Other details') recaptcha = RecaptchaField() submit = SubmitField() def __init___(self, *args, **kwargs): super(MessageForm, self).__init__(*args, **kwargs) self.msg = None self.raw_message = None self.logger = app.logger def validate(self): if not Form.validate(self): return False self.raw_message = flask.request.files["message"].stream.read() try: digest = pyzor.digest.DataDigester( email.message_from_string(self.raw_message)).value if digest != self.digest.data: self.add_error("digest", "Digest does not match message.") return False client = pyzor.client.Client(timeout=20) try: response = client.check(digest) except pyzor.TimeoutError as e: self.add_error("message", "Temporary error please try again.") self.logger.warn("Timeout: %s", e) return False except pyzor.CommError as e: self.add_error("message", "Temporary error please try again.") self.logger.warn("Error: %s", e) return False if not response.is_ok(): self.add_error("message", "Temporary error please try again.") self.logger.warn("Invalid response from server: %s", response) return False if int(response["Count"]) == 0: self.add_error("message", "Message not reported as spam.") return False if int(response["WL-Count"]) != 0: self.add_error("message", "Message is already whitelisted.") return False except AssertionError: self.add_error("message", "Invalid message.") return False return True def add_error(self, field, message): try: self.errors[field].append(message) except (KeyError, TypeError): self.errors[field] = [message]
class SceneForm(FlaskForm): """Edit the scene list for a play. Requires a list of scene numbers to be passed in when form is instantiated.""" # id = IntegerField("ID", render_kw={"readonly": True}) act = IntegerField("Act", validators=[DataRequired(), Length(1, 3)]) scene = IntegerField("Scene", validators=[DataRequired(), Length(1, 3)]) title = StringField("Title", validators=[Length(1, 100)]) description = TextAreaField("Description", validators=[Length(1, 1000)]) quote = TextAreaField("Quote", validators=[Length(1, 1000)]) image = FileField("Image", validators=[ FileAllowed(["jpg", "jpeg", "png", "bmp", "gif"], "Images files only.") ], render_kw={"class": "form-control"}) image_url = StringField("Image URL") submit = SubmitField("Submit")
class GuessForm(RoundForm): name = SelectField(choices=[GUESSER_NAME_PLACEHOLDER], validators=[_GuessUserName()]) guess_field = TextAreaField('Pair each recommender with their rec number', render_kw={"rows": 3}, validators=[DataRequired(), _GuessField()]) submit_guess = SubmitField('Guess')
class JarrettReport(FlaskForm): weeks = get_weeks title = StringField('Title', validators=[DataRequired()]) week = SelectField('Week', choices=get_weeks(include_zero=True), validators=[DataRequired()]) report = TextAreaField('Report', validators=[DataRequired()]) submit = SubmitField('Create Report')
class requestCourseForm(FlaskForm): title = StringField('Title of your request', validators=[ DataRequired('Data required')]) course_id = StringField('Assignment Id', validators=[ DataRequired('Data required')]) details = TextAreaField('Details') attachments = MultipleFileField('Attachments') submit = SubmitField('Submit')
class AdminEmailForm(FlaskForm): username = StringField('Username', validators=[DataRequired('field is required.')]) subject = StringField('Subject', validators=[DataRequired('field is required.')]) message = TextAreaField('Message', validators=[DataRequired('field is required.')]) submit = SubmitField('Send Message')
class RecipeForm(FlaskForm): """Form for creating a new recipe""" name = StringField('Name', validators=[Length(min=3, max=80)]) description = TextAreaField( 'Description', validators=[DataRequired(), Length(min=1, max=300)]) instructions = TextAreaField( 'Instructions', validators=[DataRequired(), Length(min=3, max=600)]) ingredients = TextAreaField( 'Ingredients', validators=[DataRequired(), Length(min=3, max=600)]) submit = SubmitField('Submit')
class EditReviewForm(FlaskForm): review_title = StringField("Review Title *", validators=[DataRequired()], render_kw={"maxlength": "140"}) review_content = TextAreaField("Review Content", validators=[Optional()], render_kw={"rows": "8"}) submit_review = SubmitField("Save")
class RegistrationForm(FlaskForm): username = create_uname_field() password = create_password_field() fullname = StringField('Fullname', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired(), Email()]) location = StringField('Location', validators=[DataRequired()]) biography = TextAreaField(label="Biography", validators=[DataRequired()]) photo = create_photo_field()
class ContactForm(FlaskForm): name = StringField("name", validators=[DataRequired(), Length(min=2, max=12)]) email = StringField("email", validators=[DataRequired(), Email()]) message = TextAreaField("message", validators=[DataRequired(), Length(min=5)]) submit = SubmitField("SUBMIT")