class Questionnaire_Form(Form): # Let's hardcode some data. # First, income levels: income_levels = ["0-30,000", "30,001-48,000", "48,001-75,000", "75,001-110,000", "over 110,000"] income_choices = [("", "")] for level in income_levels: if level == "over 110,000": income_choices.append((level, "Over $110,000")) else: income_choices.append((level, "$"+level)) # Next, US states: states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"] state_choices = [("", "")] for state in states: state_choices.append((state, state)) # Last, budget categories: budget_choices = [ ("", ""), ("10000", "Less than $10,000"), ("20000", "$10,000 - $20,000"), ("40000", "$20,000 - $40,000"), ("60000", "$40,000 - $60,000"), ("80000", "$60,000 - $80,000"), ("100000", "$80,000 - $100k"), ("120000", "$100k - $120k"), ("150000", "$120k - $150k"), ("200000", "$150k - $200k"), ("300000", "More than $200k") ] # With that out of the way, let's generate some fields! first_name = StringField("First name:", validators = [Required("Please enter your first name.")]) last_name = StringField("Last name:", validators = [Required("Please enter your last name.")]) email = EmailField("Email:", validators = [Required("Please enter your email."), Email("Please enter a valid email address.")]) photo = FileField("Photo:", validators = [FileAllowed(["jpg", "png", "jpeg"], "Your photo needs to be either a JPEG or PNG. Sorry!")]) career = SelectQueryField("Career:", query = Career.select().join(Recipe).distinct().where(Recipe.career == Career.id), get_label = "name", allow_blank = True, blank_text = " ", validators = [Required("Please choose a career.")]) appeal = TextAreaField("Why does this career appeal to you?") experience = TextAreaField("Do you have any experiences related to the career you chose?") income = SelectField("What's your family's income level?", choices = income_choices, validators = [Required("Please select your family's income level.")]) budget = SelectField("What's your budget for higher education?", choices = budget_choices, validators = [Required("Please enter a budget.")]) list_of_choices = ["Personal savings", "Student loans", "Help from parents or relatives", "Federal grants", "Scholarships or private grants"] choices = [(x, x) for x in list_of_choices] payment = MultiCheckboxField("How do you plan to pay for college?", choices = choices) scholarships = StringField("If you're expecting to receive scholarships or private grants, how much do you expect total?") gpa = StringField("What's your high school GPA?") test_score = StringField("What's your SAT or ACT score?") city = StringField("What city do you live in?", validators = [Required("Please enter the city you live in.")]) state = SelectField("What state do you live in?", choices = state_choices, validators = [Required("Please enter the state you live in.")]) stay_home = RadioField("Is it important to you to stay close to home?", choices = [("Yes", "Yes"), ("No", "No")]) considering = StringField("What's a college you're already considering?") alternatives = RadioField("Are you willing to consider online & alternative schools?", choices = [("Yes", "Yes"), ("No", "No")]) misc = TextAreaField("Do you have any additional needs we should know about?")
class PhotoForm(Form): photo = FileField("上传图片!", validators=[ FileRequired(), FileAllowed(['jpg', 'png', 'gif'], '只能传jpg,png,gif') ]) submit = SubmitField('上传')
class AvatarForm(Form): avatar = FileField('avatar', validators=[ FileRequired(), FileAllowed(['jpg', 'png'], 'Images only!') ]) submit = SubmitField()
class Register(FlaskForm): username = StringField( '用户名', validators=[DataRequired(), Length(6, 10, message='长度为6到10个字符之间')]) password = PasswordField( '密码', validators=[DataRequired(), Length(6, 10, message='密码必须是6到10位字符')]) password_confirm = PasswordField( '确认密码', validators=[EqualTo('password', message='两次输入密码不同')]) email = StringField('邮箱', validators=[Email(message='请输入正确到邮箱地址')]) verify_code = StringField( '验证码', validators=[DataRequired(), Length(4, 4, message='请输入4位数验证码')]) icon = FileField('头像', validators=[ FileRequired(message='请选择上传的头像'), FileAllowed(photos, message='只能上传图片') ]) submit = SubmitField('立即注册') # 自定义表单验证 def validate_username(self, field): user = User.query.filter_by(username=field.data) if user.first(): # raise 是引发异常 后面跟error名称 raise ValidationError('该用户已存在') def validate_email(self, field): email = User.query.filter_by(email=field.data) if email.first(): raise ValidationError('该邮箱已被注册')
class UploadForm(Form): ''' Form to upload SCARF results and package source ''' parsed_results = FileField( 'Select parsed results XML file', validators=[FileRequired(), FileAllowed(['xml'])]) pkg_src_archive = FileField( 'Select package source archive', validators=[FileRequired(), FileAllowed(['zip', 'tar.gz', 'tar'])]) pkg_short_name = TextField('Package short name', validators=[Required()]) pkg_version = TextField('Package version', validators=[Required()]) platform = TextField('Platform', validators=[Required()]) submit = SubmitField('Submit')
class RecipeForm(Form): """Basic form which allows to add or to edit a recipe.""" category = QuerySelectField('category_id', query_factory=categories, get_label='name', allow_blank=True, blank_text=u'Choose category', validators=[Required()]) title = StringField('title', validators=[Required(), Length(min=1, max=200)]) description = TextAreaField( 'description', validators=[Required(), Length(min=1, max=500)]) ingredients = TextAreaField( 'ingredients', validators=[Required(), Length(min=1, max=4000)]) directions = TextAreaField( 'directions', validators=[Required(), Length(min=1, max=4000)]) prep_time = IntegerField( 'prep_time', validators=[Required(), NumberRange(min=1, max=300)]) cook_time = IntegerField( 'cook_time', validators=[Required(), NumberRange(min=1, max=300)]) servings = IntegerField( 'servings', validators=[Required(), NumberRange(min=1, max=100)]) image1 = FileField('image_1', validators=[ FileAllowed(['jpeg', 'jpg', 'png'], 'Only images are allowed!') ]) image2 = FileField('image_2', validators=[ FileAllowed(['jpeg', 'jpg', 'png'], 'Only images are allowed!') ]) image3 = FileField('image_3', validators=[ FileAllowed(['jpeg', 'jpg', 'png'], 'Only images are allowed!') ])
class UploadForm(Form): upload = FileField('Upload a file:', validators=[ FileRequired(), FileAllowed(app.config['ALLOWED_EXTENSIONS'], "not allowed") ]) submit = SubmitField("Upload")
class PhaseOneForm(Form): presentation = FileField('Presentation in PDF Format', validators=[ FileRequired(), FileAllowed(['pdf'], 'Please upload in PDF format.') ]) submit = SubmitField("Send")
class BulletinForm(Form): id = HiddenField('id') # dt = DateTimeField('发布时间', format = '%Y-%m-%d %H:%M:%S') title = StringField('标题') content = TextAreaField('详情') valid = BooleanField('是否有效') source = StringField('来源') image = FileField('上传图片', validators=[FileAllowed(['jpg', 'png'], 'Images only!')])
class FinalRoundForm(Form): presentation = FileField( 'Presentation in PDF, PPTX, or PPT Format. Can include video formats M4V and MOV - must wrap everything in a ZIP file.', validators=[ FileRequired(), FileAllowed(['pdf', 'pptx', 'ppt', 'zip'], 'Please only upload in one of the allowed formats.') ]) submit = SubmitField("Send")
class TaskForm(Form): title = StringField('title', validators=[DataRequired()]) content = FileField('file', validators=[ validators.Required(), FileAllowed(['txt', 'md'], 'txt or md file') ]) input_file = FileField('file') output_file = FileField('file')
class UploadForm(Form): """ upload file """ file = FileField('Upload', validators=[ FileAllowed(['csv', 'xls', 'xlsx'], "Format of upload file can't distinguish"), FileRequired("no file upload") ]) submit = SubmitField('Upload')
class MyUploadForm(Form): """ Proof of concept form class for image upload by user """ name = TextField('name', validators=[DataRequired()]) upload = FileField( 'image', validators=[FileRequired(), FileAllowed(images, 'Images only!')])
class CategoryForm(Form): """Basic form which allows to add or to edit a category.""" name = StringField('name', validators=[Required(), Length(min=1, max=20)]) description = TextAreaField( 'description', validators=[Required(), Length(min=1, max=500)]) image = FileField('image', validators=[ FileAllowed(['jpeg', 'jpg', 'png'], 'Only images are allowed!') ])
class ImportJSonForm(Form): """ Form to import a deck to the application """ file = FileField(validators=[ FileRequired(), FileAllowed(["json", "Json Format only !"]) ]) def __init__(self, label=None): super().__init__() self.file.label = label
class NewPatientForm(Form): binding_predictor_choices = {'random': 'Random', 'netmhccons': 'NetMHCCons', 'netmhcpan': 'NetMHCPan'} display_id = TextField('Patient ID', validators=[validators.required(), validators.length(max=1000)]) vcf_file = FileField('VCF/MAF File', validators=[ FileRequired(), FileAllowed(['vcf', 'maf'], 'Variant file must be VCF or MAF')] ) hla_file = FileField('HLA File', validators=[FileRequired(), FileAllowed(['hla'], 'HLA Only')]) rna_file = FileField('RNA Expression Quantification File', validators=[FileAllowed(['txt'], 'TXT Only')]) binding_predictor = SelectField('MHC Binding Prediction', choices=sorted(zip(binding_predictor_choices.keys(), binding_predictor_choices.values())), validators=[validators.required()]) submit = SubmitField('Send')
class AvatarForm(Form): avatar_url = FileField(u'头像图片', validators=[ FileRequired(), FileAllowed(['jpg', 'jpeg', 'png'], u'只能上传jpg,jpeg,png类型图片') ]) x1 = StringField(u'x1') y1 = StringField(u'y1') x2 = StringField(u'x2') y2 = StringField(u'y2') w = StringField(u'w') h = StringField(u'h')
class MessageForm(Form): title = StringField(u'Заголовок:', validators = [DataRequired(u'Необходимо заполнить заголовок'), Length(max=config.MODEL_TITLE,min=10, message=u'Заголовок должен быть от 10 до {0} символов'.format(config.MODEL_TITLE))]) message = TextAreaField(u'Сообщение:', validators = [DataRequired(u'Необходимо заполнить тело сообщения'), Length(max=config.MODEL_MESSAGE,min=10, message=u'Тело сообщения должно быть от 10 до {0} символов'.format(config.MODEL_MESSAGE))]) email = StringField(u'Почта:', validators = [Email(u'Неправильно введён Email'), Optional(), Length(max=config.MODEL_EMAIL, message=u'Email должен быть не более {0} символов'.format(config.MODEL_EMAIL))]) #inputtext (email, telephone, etc) telephone = StringField(u'Телефон:', validators = [Optional(), Regexp('(\d{0,3})\(\d{3,5}\)\d{5,7}(?:#\d{2,4}|)',flags=0, message=u'Телефонный номер должен быть представлен в указанном формате'), Length(max=config.MODEL_TELEPHONE, message=u'Телефонный номер должен быть не более {0} символов'.format(config.MODEL_TELEPHONE))]) #inputtext (email, telephone, etc) archive = FileField(u'Файл:', validators=[Optional(), FileAllowed(['zip'], u'Файл должен быть zip-архивом!')]) recaptcha = RecaptchaField() send_button = SubmitField(u'Отправить') def __init__(self, *args, **kwargs): super(MessageForm, self).__init__(*args, **kwargs) self.contacts = u'' def validate(self): initial_validation = super(MessageForm, self).validate() if not initial_validation: print "MessageForm: initial_validation failed" return False if self.send_button.data: if not self.email.data and not self.telephone.data : self.email.errors.append(u'Должны быть указаны контактные данные (хотя бы email)') self.telephone.errors.append(u'Должны быть указаны контактные данные (хотя бы телефон)') #print u'Email ' + self.email.data.encode('utf-8') + u' and Telefone ' + self.telephone.data.encode('utf-8') + u' not set' return False elif self.email.data and self.telephone.data : self.contacts = self.email.data + u', ' + self.telephone.data #print self.contacts.encode('utf-8') elif self.email.data and not self.telephone.data : self.contacts = self.email.data #print self.contacts.encode('utf-8') else : self.contacts = self.telephone.data return True # Any data is ok
class SignUpForm(Form): username = StringField('Username: '******'Firstname: ', validators=[DataRequired()]) lastname = StringField('Lastname: ', validators=[DataRequired()]) age = IntegerField('Age: ', validators=[DataRequired()]) gender = SelectField('Gender: ', choices=[('Male', 'Male'), ('Female', 'Female')]) image = FileField('Profile Picture: ', validators=[ FileRequired(), FileAllowed(['jpg', 'jpeg', 'png', 'gif'], 'Images Only') ]) userid = HiddenField() submit = SubmitField('Submit')
class InstitutionForm(Form): id = HiddenField('id') name = StringField('品牌名', validators=[Length(min=1, max=50)]) agespan_id = SelectField(u'招生年龄', coerce=int) area_id = SelectField(u'所在区县', coerce=int) address = StringField('地址') # location = StringField('校区名') website = StringField('网址') # telephone = StringField('电话') feedesc = StringField('学费标准') # timeopen = DateTimeField('开业时间', format='%H:%M') timeclose = DateTimeField('关门时间', format='%H:%M') feetype_id = SelectField('收费类型', coerce=int) longitude = DecimalField('经度', places=4) latitude = DecimalField('纬度', places=4) #featuredesc = db.Column(db.String(200)) #特色小项描述 feature_ids = SelectMultipleField(u'培训方向', coerce=int) image = FileField('上传图片', validators=[FileAllowed(['jpg', 'png'], 'Images only!')])
class SchoolForm(Form): id = HiddenField('id') name = StringField('学校名称', validators=[Length(min=1, max=50)]) # 学校名称 area_id = SelectField(u'所在区县', coerce=int) #区县 teachdesc = TextAreaField(u'校长及教师情况') # address = StringField('地址') # schooltype_id = SelectField(u'学校类型', coerce=int) # website = StringField('网址') # distinguish = TextAreaField(u'教学特色') # leisure = TextAreaField(u'课外特色活动') # threashold = TextAreaField(u'招生条件及招生地块') # partner = StringField('对口学校') # artsource = StringField('艺术特长招生情况') # feedesc = StringField('学费标准') # longitude = DecimalField('经度', places=4) latitude = DecimalField('纬度', places=4) feature_ids = SelectMultipleField(u'教学特色', coerce=int) image = FileField('上传图片', validators=[FileAllowed(['jpg', 'png'], 'Images only!')])
class VoterEditForm(Form): dpi = StringField('DPI :', validators=[required('DPI is required.')]) name = StringField('Name :', validators=[required('Name is required.')]) email = StringField('Email :', validators=[required('Email is required.'), email()]) phone = StringField('Phone :') city_id = SelectField('Location :', coerce=int) referred = TextAreaField('Referred :') photo = FileField('Photo :', validators=[FileAllowed(['jpg', 'png', 'jpeg'], 'Invalid image!')]) submit = SubmitField('Save') def __init__(self, *args, **kwargs): super(VoterEditForm, self).__init__(*args, **kwargs) self.city_id.choices = [(city.id, city.department_nam + '/' + city.city_nam) for city in City.query.order_by('department_nam', 'city_nam').all()] self.old_dpi = kwargs['obj'].dpi def validate_dpi(self, field): if Voter.query.filter_by(dpi=field.data).first() and self.dpi.data != self.old_dpi: raise ValidationError('Voter with DPI already exists.')
class RentForm(Form): id = HiddenField('id') title = StringField(u'标题', validators=[Required(), Length(1, 64)]) price = IntegerField(u'租金') description = TextAreaField(u'描述') area_id = SelectField(u'所在区县', coerce=int) mode_id = SelectField(u'出租方式', coerce=int) rent_type = SelectField(u'押金方式', validators=[Required()], choices=[('0', u'押一付一'), ('1', u'押一付三')]) contacts = StringField(u'联系人') phone_number = IntegerField(u'联系方式') residential_id = SelectField(u'小区', coerce=int) size = StringField(u'面积') address = StringField(u'地址') subway_line = SelectField(u'地铁线', coerce=int) decorate_type = SelectField(u'装修情况', validators=[Required()], choices=[('0', u'简单装修'), ('1', u'精装修')]) image = FileField('上传图片', validators=[FileAllowed(['jpg', 'png'], 'Images only!')])
class VoterForm(Form): dpi = StringField('DPI :', validators=[required('DPI is required.')]) name = StringField('Name :', validators=[required('Name is required.')]) email = StringField('Email :', validators=[required('Email is required.'), email()]) phone = StringField('Phone :') department = SelectField('Department :', coerce=int) city_id = SelectField('Location :', coerce=int) referred = TextAreaField('Referred :') photo = FileField('Photo :', validators=[FileAllowed(['jpg', 'png', 'jpeg'], 'Invalid image!')]) submit = SubmitField('Save') def __init__(self, *args, **kwargs): super(VoterForm, self).__init__(*args, **kwargs) self.city_id.choices = [(city.id, city.department_nam + '/' + city.city_nam) for city in City.query.order_by('department_nam', 'city_nam').all()] query = db.session.query(City.department_nam.distinct().label("department")) self.department.choices = [(i, row.department) for i, row in enumerate(query.order_by('department').all())] def validate_dpi(self, field): if Voter.query.filter_by(dpi=field.data).first(): raise ValidationError('Voter with DPI already exists.')
class EditForm(Form): nickname = StringField('nickname', validators=[DataRequired()]) about_me = TextAreaField('about_me', validators=[Length(min=0, max=140)]) profile_photo = FileField( 'Your photo', validators=[FileAllowed(['jpg', 'png'], 'Images only!')]) def __init__(self, *args, **kwargs): Form.__init__(self, *args, **kwargs) def validate(self, current_user=None): if not Form.validate(self): return False if self.nickname.data != User.make_valid_nickname(self.nickname.data): self.nickname.errors.append( 'This nickname has invalid characters. ' 'Please use letters, numbers, dots and underscores only.') return False user = User.query.filter_by(nickname=self.nickname.data).first() if user is not None: if user.id is not current_user.id: self.nickname.errors.append('This nickname is already in use.') return False return True
class NewMentorPhoto(Form): name = TextField("Name", [validators.Required("Please enter mentor name")]) position = TextField("Position", [validators.Required("Please enter mentor position")]) organization = TextField( "Organization", [validators.Required("Please enter mentor organization")]) bio = TextAreaField("Bio", [validators.Required("Please enter mentor bio")]) photo = FileField('Photo', validators=[ FileAllowed(['jpg', 'png', 'gif'], 'Please upload image file.') ]) def validate(self): if not Form.validate(self): return False mentorphoto = Judge.query.filter_by(name=self.name.data).first() if mentorphoto: return False else: return True
class HistoryForm(Form): fileName = FileField( 'hfile', validators=[FileRequired(), FileAllowed(['txt'], 'Text Files Only!')]) submit = SubmitField("Submit")
class GroupForm(Form): name = StringField('小组名称', validators=[Required('必填项'), Length(1, 24, '名称最长24个字符')]) icon = FileField('小组图标(建议尺寸120px*120px,只限jpg和png格式)', validators=[Required('小组图标必须有'), FileAllowed(['jpg', 'png'], '只限jpg和png格式')]) intro = TextAreaField('介绍', validators=[Required('说说这个小组的事儿嘛')]) save = SubmitField('确认')
class AddCategoryForm(Form): name = TextField('Name', validators=[Required()]) description = TextAreaField() image = FileField( 'Image', validators=[FileAllowed(category_img, message="Images Only!!")])
class Add_Career(Form): name = StringField("Name", validators = [Required("Don't forget the career's name!")]) image = FileField("Banner image", validators = [FileAllowed(["jpg", "png", "jpeg"], "You sure that's an image file? Upload a JPEG or PNG!")]) description = TextAreaField("Description")