class JacksForm(wtforms.Form): raw_count_file = wtforms.FileField('Raw count file', validators=[DataRequired()]) replicate_map_file = wtforms.FileField('Replicate map file', validators=[DataRequired()]) header_replicates = wtforms.StringField('Header for replicates', default=REP_HDR_DEFAULT) header_sample = wtforms.StringField('Header for sample', default=SAMPLE_HDR_DEFAULT) ctrl_sample_name = wtforms.StringField('Name for a control sample', default="CTRL") grna_gene_map_file = wtforms.FileField('gRNA-Gene map file', validators=[DataRequired()]) header_grna = wtforms.StringField('Header for gRNA id', default=SGRNA_HDR_DEFAULT) header_gene = wtforms.StringField('Header for Gene', default=GENE_HDR_DEFAULT) use_reference_lib = wtforms.BooleanField('Use reference library', default=False) reference_lib = wtforms.SelectField( 'Reference library', choices=[ ("", 'None'), (YUSAV1_0, 'Yusa v1.0'), # ('yusav1.1', 'Yusa v1.1'), (AVANA, 'Avana') ], # ('brunello', 'Brunello'), # ('whitehead', 'Whitehead'), # ('toronto', 'Toronto Knockout')], default="")
class FieldRendererForm(Form): textfield = wt.TextField('My Text Field', widget=wt_bs.TextInput()) textfield_no = wt.TextField('My Text Field Without Widget') # Declare a textField to use a PasswordInput (Example 1) passwordfield = wt.TextField('My Pass Field', widget=wt_bs.PasswordInput()) passwordfield_no = wt.TextField('My Pass Field Without Widget') filefield = wt.FileField('My File Upload', widget=wt_bs.FileInput()) filefield_no = wt.FileField('My File Upload Without Widget')
class AddCandidateForm(flask_wtf.Form): ''' Form to add a candidate to an election. ''' candidate_name = wtf.TextField( 'Title', [wtf.validators.Required()]) candidate_author = wtf.TextField( 'Author', [wtf.validators.Required()]) candidate_original_url = wtf.TextField( 'URL to the original artwork') candidate_file = wtf.FileField( 'File', [wtf.validators.Required()]) candidate_license = wtf.SelectField( 'License', [wtf.validators.Required()], choices=[ (None, ''), ('CC0', 'CC0'), ('CC-BY', 'CC-BY'), ('CC-BY-SA', 'CC-BY-SA'), ('DSL', 'DSL'), ('Free Art', 'Free Art'), ]) def __init__(self, *args, **kwargs): ''' Calls the default constructor and fill in default values. ''' super(AddCandidateForm, self).__init__(*args, **kwargs)
class PlottypeForm(wtf.Form): plot_type = wtf.SelectField(label="Plot type", choices=['RTI','Convection','Fan']) filename = wtf.FileField(default=None, label='filename', description='filename', validators=[wtf.validators.InputRequired()])
class DocUploadForm(wtforms.Form): name = wtforms.StringField( 'Package Name', validators=[wtvalidators.DataRequired('No package name given')]) content = wtforms.FileField('Documentation Zip') @staticmethod def validate_content(form, field): if field.data.bufsize > 100 * 1024 * 1024: raise wtvalidators.ValidationError('ZIP file is too large') data_file = field.data.file if not zipfile.is_zipfile(data_file): raise wtvalidators.ValidationError('ZIP file is not a zipfile') zip_file = zipfile.ZipFile(data_file) members = zip_file.namelist() if 'index.html' not in members: raise wtvalidators.ValidationError( 'Top-level "index.html" missing in the ZIP file') base_dir = tempfile.mkdtemp() try: for name in members: if not os.path.normpath(os.path.join( base_dir, name)).startswith(base_dir): raise wtvalidators.ValidationError( 'Invalid path name %s in the ZIP file', name) finally: os.rmdir(base_dir) data_file.seek(0)
class EditSubtitlesForm(wtforms.Form): subtitle_language = wtforms.StringField('Language') subtitle_file = wtforms.FileField( 'File', description= _('Subtitles in <a href="https://en.wikipedia.org/wiki/WebVTT" target="_blank">WebVTT format</a>' ))
def get_form(self, **kwargs): """Erzeuge Formularklasse für das Model""" # Erstmal nur das Form zurückgeben. # Soll sich doch jeder selbst um 'only' und 'exclude' kümmern, # bei model_form gehen aber leider alle Labels und Descriptions verloren. if hasattr(self, 'form'): return getattr(self, 'form') if self.exclude is None: exclude = [] else: exclude = list(self.exclude) defaults = { 'base_class': self.form, 'only': self.fields, 'exclude': (exclude + kwargs.get('exclude', [])) or None, } klass = model_form(self.model, **defaults) # label könnte man noch setzbar machen for blob_upload_field in self.blob_upload_fields: field = wtforms.FileField() setattr(klass, blob_upload_field, field) return klass
class UpdatePost(flask_wtf.FlaskForm): topic = wtforms.SelectField('Choose the topic', choices=choices) heading = wtforms.TextAreaField('Heading') post_preview = wtforms.TextAreaField('Post preview') post_text = wtforms.TextAreaField('Post text') image = wtforms.FileField('Post image', [wtforms.validators.DataRequired()]) submit = wtforms.SubmitField('Update post') # Pre-filling the form by data from the post def retrieve(self, topic, heading, post_preview, post_text, image): self.topic.data = topic self.heading.data = heading self.post_preview.data = post_preview self.post_text.data = post_text self.image.data = image # sending the updated data to the table def sending_updated_data(self, post_id): topic_n = self.topic.data heading_n = self.heading.data post_preview_n = self.post_preview.data post_text_n = self.post_text.data post_image_n = images.save(self.image.data) post = models.Post.query.filter_by(post_id=post_id).first() post.update_post(topic_n=topic_n, heading_n=heading_n, post_preview_n=post_preview_n, post_text_n=post_text_n, post_image_n=post_image_n) return post
class ProfileEditForm( model_form(User, only=('name', 'profile', 'default_project_group_id'))): name = wtf.TextField(lazy_gettext(u'이름')) profile = wtf.TextField(lazy_gettext(u'자기소개')) # , [wtf.validators.regexp(ur'^[^/\\]\.jpg$')]) profile_imgf = wtf.FileField( lazy_gettext(u'이미지 파일'), validators=[ image_file_validator('USER_PROFILE_IMAGE_MAX_CONTENT_LENGTH'), ]) default_project_group_id = wtf.SelectField(lazy_gettext(u'시작프로젝트그룹')) def validate_default_project_group_id(form, field): if field.data == '': field.data = None def populate_obj(self, obj): """image-data는 평소에는 전달되지 않는데 None을 할당해버리면 기존 데이타가 지워져버리기 때문에 None이면 아예 처리하지 않기.""" if self.profile_imgf.data is None: setattr(self, '_profile_imgf', self.profile_imgf) del self.profile_imgf ret = super(ProfileEditForm, self).populate_obj(obj) setattr(self, 'profile_imgf', self._profile_imgf) del self._profile_imgf return ret else: return super(ProfileEditForm, self).populate_obj(obj)
class RegistrationForm(flask_wtf.FlaskForm): name = wtforms.StringField('汝是谁?', validators=[DataRequired(), Length(0, 64)]) email = wtforms.StringField( '电子邮件地址', validators=[DataRequired(), Length(0, 64), Email()]) classnum = wtforms.StringField('学号', validators=[DataRequired(), Length(8)]) gender = wtforms.SelectField('性别', validators=[DataRequired()]) phone = wtforms.StringField('电话号码', validators=[DataRequired(), Length(11, 11)]) telegram = wtforms.StringField('Telegram (用户名,不含"@")', validators=[Length(0, 64)]) personal_page = wtforms.StringField('Blog', validators=[Length(0, 64)]) ability = wtforms.TextAreaField('汝都擅长些啥咧?') desc = wtforms.TextAreaField('介绍下汝自己呗~') photo = wtforms.FileField('不留张照片?') submit = wtforms.SubmitField('就这样?') def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) self.gender.choices = [(1, "男"), (2, "女")]
class LaunchMoreInstancesForm(BaseSecureForm): """Form class for launch more instances like this one""" number_error_msg = _( u'Number of instances must be a whole number greater than 0') number = wtforms.IntegerField( label=_(u'How many instances would you like to launch?'), validators=[ validators.InputRequired(message=number_error_msg), validators.NumberRange( min=1, max=10 ), # Restrict num instances that can be launched in one go ], ) userdata = wtforms.TextAreaField(label=_(u'User data')) userdata_file_helptext = _(u'User data file may not exceed 16 KB') userdata_file = wtforms.FileField(label=_(u'')) kernel_id = wtforms.SelectField(label=_(u'Kernel ID')) ramdisk_id = wtforms.SelectField(label=_(u'RAM disk ID (RAMFS)')) monitoring_enabled = wtforms.BooleanField( label=_(u'Enable detailed monitoring')) private_addressing = wtforms.BooleanField( label=_(u'Use private addressing only')) def __init__(self, request, image=None, instance=None, conn=None, **kwargs): super(LaunchMoreInstancesForm, self).__init__(request, **kwargs) self.image = image self.instance = instance self.conn = conn self.choices_manager = ChoicesManager(conn=conn) self.set_error_messages() self.set_help_text() self.set_choices() self.set_initial_data() def set_error_messages(self): self.number.error_msg = self.number_error_msg def set_help_text(self): self.userdata_file.help_text = self.userdata_file_helptext def set_choices(self): self.kernel_id.choices = self.choices_manager.kernels(image=self.image) self.ramdisk_id.choices = self.choices_manager.ramdisks( image=self.image) def set_initial_data(self): self.monitoring_enabled.data = self.instance.monitored self.private_addressing.data = self.enable_private_addressing() self.number.data = 1 def enable_private_addressing(self): if self.instance.private_ip_address == self.instance.ip_address: return True return False
class AddSimpleForm(wtforms.Form): image = wtforms.FileField() name = wtforms.StringField( validators=[wtforms.validators.Length(min=0, max=500)]) comment = wtforms.StringField() # tags = wtforms.FieldList(wtforms.StringField()) category = wtforms.IntegerField() level = wtforms.IntegerField()
class SignUpForm(flask_wtf.FlaskForm): username = wtforms.StringField("Username: "******"Mail: ") password = wtforms.PasswordField("Password: "******"Profile picture:") submit = wtforms.SubmitField("Sign up")
class MyUpload(FormWErrors): "Form per upload di files" upload_file = wt.FileField('Aggiungi allegato', [wt.validators.Optional()]) tipo_allegato = MyAttachField() sigla_ditta = wt.TextField('') def __init__(self, choices, *p, **kw): super().__init__(*p, **kw) self.tipo_allegato.set(choices)
class CSVUploadForm(Form): raw_csv = wtf.TextAreaField('CSV Data', description="Paste in a raw CSV file") csv_file = wtf.FileField( 'CSV File', description="Upload a CSV file from your computer") queue = wtf.BooleanField('Queue for Printing', default=True, description="Queue these badges for printing now") submit = wtf.SubmitField('Upload Data')
class PlaylistForm(Form): title = wtforms.TextField(u"Title", validators=[wtforms.validators.Required()], description=u"The name of your playlist") name = wtforms.TextField( u"URL Name", validators=[wtforms.validators.Optional()], description=u"Optional. Will be automatically generated if left blank") description = TinyMce4Field(u"Description") recorded_date = wtforms.DateField( u"Recorded date", validators=[wtforms.validators.Optional()], description= u"Date on which the videos in this playlist were recorded, if applicable" ) published_date = wtforms.DateField( u"Published date", validators=[wtforms.validators.Required()], description=u"Date on which this playlist was created or made public") public = wtforms.BooleanField(u"This playlist is public", default=True) banner_image = wtforms.FileField( u"Playlist banner ad", description="Optional - Ad will be displayed in playlist page", validators=[wtforms.validators.Optional()]) banner_ad_url = wtforms.fields.html5.URLField( u"Banner Ad URL", description="URL to which user should be redirected to", validators=[wtforms.validators.Optional()]) delete_banner_ad = wtforms.BooleanField(u"Delete existing ad?") def validate_name(self, field): if invalid_name.search(field.data): raise wtforms.validators.ValidationError( "The name cannot have spaces or non-alphanumeric characters") existing = Playlist.query.filter_by(channel=self.channel, name=field.data).first() if existing and existing.id != self.edit_id: raise wtforms.validators.ValidationError( "That name is already in use") def validate_banner_ad(self, field): if field.data and 'banner_ad' in request.files: requestfile = request.files['banner_ad'] fileext = requestfile.filename.split('.')[-1].lower() if fileext not in [u'png', u'jpg', u'jpeg']: raise UploadNotAllowed( u"Unsupported file format. Only PNG and JPG are supported") img = Image.open(requestfile) img.load() if not img.size == BANNER_AD_ALLOWED_SIZE: raise UploadNotAllowed( u"Banner size should be %sx%s" % (BANNER_AD_ALLOWED_SIZE[0], BANNER_AD_ALLOWED_SIZE[1])) def validate_banner_ad_url(self, field): if not field.data: raise UploadNotAllowed(u"Banner Ad URL is required")
class ComicForm(wtforms.Form): title = wtforms.TextField( u'Title', [wtforms.validators.required(), wtforms.validators.length(max=50)]) comic = wtforms.FileField( u'Comic Image', [wtforms.validators.required(), comic_content_types], )
class InstanceForm(BaseSecureForm): """Instance form (to update an existing instance) Form to launch an instance is in LaunchInstanceForm """ name_error_msg = _(u'Not a valid name') name = TextEscapedField(label=_(u'Name')) instance_type_error_msg = _(u'Instance type is required') instance_type = wtforms.SelectField(label=_(u'Instance type')) userdata = wtforms.TextAreaField(label=_(u'User data')) userdata_file_helptext = _(u'User data file may not exceed 16 KB') userdata_file = wtforms.FileField(label='') monitored = wtforms.BooleanField(label=_(u'Monitoring enabled')) kernel = wtforms.SelectField(label=_(u'Kernel ID')) ramdisk = wtforms.SelectField(label=_(u'RAM disk ID (ramfs)')) security_groups = wtforms.SelectMultipleField(label=_('Security groups')) start_later = wtforms.HiddenField() def __init__(self, request, instance=None, conn=None, **kwargs): super(InstanceForm, self).__init__(request, **kwargs) self.cloud_type = request.session.get('cloud_type', 'euca') self.instance = instance self.conn = conn self.name.error_msg = self.name_error_msg self.instance_type.error_msg = self.instance_type_error_msg self.choices_manager = ChoicesManager(conn=self.conn) self.set_choices() self.userdata_file.help_text = self.userdata_file_helptext if instance is not None: self.name.data = instance.tags.get('Name', '') self.instance_type.data = instance.instance_type self.monitored.data = instance.monitored self.kernel.data = instance.kernel or '' self.ramdisk.data = instance.ramdisk or '' self.userdata.data = '' if instance.vpc_id: self.security_groups.data = sorted( [group.id for group in instance.groups]) def set_choices(self): self.instance_type.choices = self.choices_manager.instance_types( cloud_type=self.cloud_type) self.kernel.choices = self.choices_manager.kernels() self.ramdisk.choices = self.choices_manager.ramdisks() if self.instance and self.instance.vpc_id: self.security_groups.choices = self.get_security_group_choices( self.instance.vpc_id) def get_security_group_choices(self, vpc_id): choices = [] security_groups = self.conn.get_all_security_groups( filters={'vpc-id': [vpc_id]}) for group in security_groups: value = group.id label = '{0} ({1})'.format(group.name, group.id) choices.append((value, label)) return sorted(choices, key=lambda x: x[1])
class ItemsForm(FlaskForm): name = wtf.StringField("Nome", [wtf.validators.DataRequired()]) image = wtf.FileField("Image", [wtf.validators.DataRequired()]) price = wtf.FloatField("Preço", [wtf.validators.DataRequired()]) quantity = wtf.IntegerField("Quantidade", [wtf.validators.DataRequired()]) description = wtf.TextAreaField("Descrição", [wtf.validators.DataRequired()]) store_id = QuerySelectField('ID da loja', query_factory=lambda: Store.query.all()) available = wtf.BooleanField("Disponivel", default=True)
class StacksUpdateForm(BaseSecureForm): """Stacks update form. Only need to initialize as a secure form to generate CSRF token """ template_file_helptext = _(u'Template file may not exceed 16 KB') template_file = wtforms.FileField(label='') def __init__(self, request, s3_bucket, **kwargs): super(StacksUpdateForm, self).__init__(request, **kwargs) self.template_file.help_text = self.template_file_helptext
class ProfileForm(BaseForm): nickname = wtforms.TextField(_l("Display name"), ) avatar = wtforms.FileField(_l("Avatar")) profile_access_model = wtforms.RadioField( _l("Profile visibility"), choices=_ACCESS_MODEL_CHOICES, ) action_save = wtforms.SubmitField(_l("Update profile"), )
class FileUploadForm(ReactorForm): title = wtforms.StringField('File Title', default=default_filename, validators=[wtforms.validators.DataRequired()]) file = wtforms.FileField('File') def validate_file(self, field): if not hasattr(field.data, 'file'): raise wtforms.ValidationError('File is missing') submit = wtforms.SubmitField(_('Upload'))
class Zernike(wtf.Form): filename = wtf.FileField(validators=[wtf.validators.InputRequired()]) defocus = wtf.FloatField(label="Defocus", default=None) astigmatism_1 = wtf.FloatField(label="Astigmatism", default=None) astigmatism_2 = wtf.FloatField(label="Astigmatism", default=None) coma_1 = wtf.FloatField(label="Coma", default=None) coma_2 = wtf.FloatField(label="Coma", default=None) coma_3 = wtf.FloatField(label="Coma", default=None) coma_4 = wtf.FloatField(label="Coma", default=None) higher_order = wtf.BooleanField(label="Higher-Order Aberrations", default=True)
class PodcastCreateForm(wtforms.Form): file = wtforms.FileField(_('Image'), description=desc) title = wtforms.TextField(_('Title'), [wtforms.validators.Length(min=0, max=500)]) adminemail = wtforms.TextField( _('Admin Email'), [wtforms.validators.Length(min=0, max=500)]) description = wtforms.TextAreaField(_('Description of the Podcast')) max_file_size = wtforms.HiddenField('') upload_limit = wtforms.HiddenField('') uploaded = wtforms.HiddenField('')
class ArticleForm(FlaskForm): title = form.StringField( 'Title', validators=[validator.DataRequired(), validator.Length(max=100)]) summary = form.TextAreaField('Summary', validators=[validator.DataRequired()]) content = form.TextAreaField('Content', validators=[validator.DataRequired()]) # tags = form.SelectMultipleField('Tags', validators=[validator.Optional()], choices=[(1, 1), (2,2)]) image = form.FileField('Image', validators=[validator.Optional()]) is_published = form.BooleanField('Is Active', default=True)
class RecipeEdit(Form): START_NUM_INGREDIENTS = RECIPE_START_NUM_INGREDIENTS MIN_INGREDIENTS = RECIPE_MIN_INGREDIENTS MIN_GROUPS = RECIPE_MIN_GROUPS title = wtf.TextField("Title") description = wtf.TextAreaField("Description") instructions = wtf.TextAreaField("Instructions") photo = wtf.FileField("Photo", validators=[valid_photo]) tags = TagListField("Tags", validators=[valid_tags]) general_ingredients = wtf.FieldList(wtf.FormField(IngredientForm), min_entries=RECIPE_MIN_INGREDIENTS, max_entries=RECIPE_MAX_INGREDIENTS) ingredient_groups = wtf.FieldList(wtf.FormField(IngredientGroup), min_entries=RECIPE_MIN_GROUPS, max_entries=RECIPE_MAX_GROUPS) @classmethod def from_recipe(cls, recipe, *args, **orig_kwargs): kwargs = dict(orig_kwargs) kwargs['title'] = recipe.title kwargs['description'] = recipe.description kwargs['instructions'] = recipe.instructions kwargs['general_ingredients'] = [ IngredientForm.from_model(i) for i in recipe.general_ingredients ] kwargs['ingredient_groups'] = [ IngredientGroup.from_model(g) for g in recipe.ingredient_groups ] kwargs['tags'] = recipe.tags return cls(*args, **kwargs) def save_recipe(self, recipe): """ Update a recipe from the form data """ if self.photo.data: recipe.photo = photos.save(self.photo.data.stream) recipe.title = self.title.data recipe.title_slug = slugify(self.title.data) recipe.description = self.description.data recipe.instructions = self.instructions.data recipe.general_ingredients = [ i.to_model() for i in self.general_ingredients ] recipe.ingredient_groups = [ g.to_model() for g in self.ingredient_groups ] recipe.tags = self.tags.data recipe.save()
class Products(flask_wtf.FlaskForm): name = wtforms.StringField( 'Name', [validators.DataRequired(), validators.Length(max=30)]) price = wtforms.IntegerField('Price', [validators.DataRequired()]) category = wtforms.SelectField('Category', choices=[('laps', 'Laptops'), ('phone', 'Mobile Phones'), ('acc', 'Accessories')]) stock = wtforms.IntegerField('Stock') image = wtforms.FileField('Image Upload') submit = wtforms.SubmitField('Submit')
class FileUploadForm(ReactorForm): title = wtforms.StringField( "File Title", default=default_filename, validators=[wtforms.validators.DataRequired()], ) file = wtforms.FileField("File") def validate_file(self, field): if not hasattr(field.data, "file"): raise wtforms.ValidationError("File is missing") submit = wtforms.SubmitField(_("Upload"))
class SheetForm(CSRFForm): piece = form_field_from_model(Sheet, "piece") composers = form_field_from_model(Sheet, "composers", field_class=ListField) genre = form_field_from_model(Sheet, "genre") tags = form_field_from_model(Sheet, "tags", field_class=ListField) instruments = form_field_from_model(Sheet, "instruments", field_class=ListField) type = form_field_from_model(Sheet, "type") catalog_number = form_field_from_model(Sheet, "catalog_number") sheet_file = wtforms.FileField("Sheet File", validators=[InputRequired()]) submit = wtforms.SubmitField()
class LocationForm(Form): """ Form to input conference guest locations """ meeting_name = wtforms.StringField('meeting_name', validators=[validators.DataRequired(message="Must provide a name")]) opt_message = "Only one of text form locations or file upload containing locations is required" locations = wtforms.TextAreaField('locations', validators=[NotRequiredIf("file_locations", message=opt_message)]) file_locations = wtforms.FileField('file_locations', validators=[NotRequiredIf('locations', message=opt_message)])