예제 #1
0
파일: forms.py 프로젝트: xeonpc/WanMuJia
class RegistrationForm(Form):
    email = StringField(validators=[Email(message=u'邮箱不正确')])
    agent_name = StringField(validators=[Length(1, 10, u'代理人姓名不正确')])
    agent_identity = StringField(validators=[Length(18, 18, u'代理人身份证号码不正确')])
    agent_identity_front = FileField(validators=[Image(required=True, base64=True, message=u'身份证正面照片不正确')])
    agent_identity_back = FileField(validators=[Image(required=True, base64=True, message=u'身份证反面照片不正确')])
    license_image = FileField(validators=[Image(required=True, base64=True, message=u'营业执照照片不正确')])
    name = StringField(validators=[Length(2, 30, u'品牌厂商名称不正确')])
    license_limit = StringField(validators=[Length(8, 10, u'营业执照期限不正确')])
    telephone = StringField(validators=[Length(7, 15, u'固话不正确')])
    address = StringField(validators=[Length(1, 30, u'地址不正确')])
    area_cn_id = StringField(validators=[AreaValidator(), Length(6, 6)])
    brand = StringField(validators=[Brand(exist_owner=current_user)])

    image_fields = ('agent_identity_front', 'agent_identity_back', 'license_image')

    def validate_license_limit(self, field):
        try:
            date = list(map(int, field.data.split('/')))
            limit = datetime.datetime(date[0], date[1], date[2])
        except ValueError:
            raise ValidationError(u'营业执照期限格式不正确')
        self.license_limit.data = limit.strftime('%G/%m/%d')

    def save_images(self, vendor=None):
        vendor = vendor if vendor else current_user
        for image_field in self.image_fields:
            if getattr(self, image_field).data:
                image, image_hash = save_image(vendor.id, 'vendor', getattr(self, image_field),
                                               IO(b64decode(getattr(self, image_field).data[23:])))
                setattr(vendor, image_field, image)
                db.session.add(vendor)
            db.session.commit()
예제 #2
0
  def __init__(self, *args, **kwargs):
    try:
      self.multiple = kwargs.pop('multiple')
    except KeyError:
      pass

    BaseFileField.__init__(self, *args, **kwargs)
예제 #3
0
파일: forms.py 프로젝트: xeonpc/WanMuJia
class ReconfirmForm(RegistrationForm):
    email = None
    agent_identity_front = FileField(validators=[Image(required=False, base64=True, message=u'身份证正面照片不正确')])
    agent_identity_back = FileField(validators=[Image(required=False, base64=True, message=u'身份证反面照片不正确')])
    license_image = FileField(validators=[Image(required=False, base64=True, message=u'营业执照照片不正确')])

    is_reconfirm = True

    address_attributes = ('province', 'city', 'district')
    attributes = ('agent_name', 'agent_identity', 'name', 'license_limit', 'telephone', 'brand')
    url_attributes = ('agent_identity_front', 'agent_identity_back', 'license_image', 'logo')

    def update_address(self):
        current_user.address.address = self.address.data
        current_user.address.cn_id = self.area_cn_id.data
        db.session.add(current_user.address)
        db.session.commit()

    def show_address(self):
        area = current_user.address.area
        if area:
            grades_id = [_.cn_id for _ in current_user.address.area.grade()]
        else:
            grades_id = []
        while len(grades_id) < 3:
            grades_id.append(None)
        for attr, cn_id in zip(self.address_attributes, grades_id):
            setattr(self, attr, cn_id)

    def show_info(self):
        for attr in self.attributes:
            getattr(self, attr).data = getattr(current_user, attr)
        for attr in self.url_attributes:
            setattr(self, attr + '_url', url_for('static', filename=getattr(current_user, attr)))
        self.address.data = current_user.address.address
        self.area_cn_id.data = current_user.address.cn_id
        self.show_address()

    def reconfirm(self):
        self.save_images()
        self.update_address()
        for attr in self.attributes:
            setattr(current_user, attr, getattr(self, attr).data)
        db.session.commit()
        current_user.flush('info_completed')
        if current_user.info_completed:
            current_user.push_confirm_reminds(VENDOR_REMINDS_PENDING)
        else:
            current_user.push_confirm_reminds(VENDOR_REMINDS_COMPLETE)
예제 #4
0
파일: forms.py 프로젝트: dodumosu/apollo
 class FileUploadForm(WTSecureForm):
     event = SelectField(_('Event'),
                         choices=_make_choices(
                             events.find().scalar('id', 'name'),
                             _('Select Event')),
                         validators=[validators.input_required()])
     spreadsheet = FileField(_('Data File'), )
예제 #5
0
class UploadForm(Form):
    file = FileField(u'资源上传', validators=[DataRequired('请上传后提交')])
    name = TextField(u'资源名称', [DataRequired(u'资源名称不能为空')])
    types = SelectField(u'类别',
                        choices=[
                            ('1', u'教学计划'), ('2', u'教学大纲'), ('3', u'教学方案'),
                            ('4', u'教材'), ('5', u'课件'), ('6', u'案例描述'),
                            ('7', u'案例参考答案'), ('8', u'试验题目'), ('9', u'实验指导'),
                            ('10', u'实验报告'), ('11', u'试卷'), ('12', u'试卷答案'),
                            ('13', u'练习')
                        ])
    format = SelectField(u'格式',
                         choices=[('1', u'文档'), ('2', u'视频'), ('3', u'音频')])
    course = SelectField(
        u'课程名称',
        choices=zip(
            list(zip(*(db.session.query(Course, Course.name).all()))[1]),
            list(zip(*(db.session.query(Course, Course.name).all()))[1])))

    url = TextField(u'资源地址', [DataRequired(u'地址不能为空'), URL(message="无效的地址")])
    author = TextField(u'作者', [DataRequired(u'作者不能为空')])
    desc = TextAreaField(u'资源描述', [DataRequired(u'描述不能为空')])
    # standard = SelectField(u'标准', choices=zip(list(zip(*(db.session.query(StandardAndSpe, StandardAndSpe.name).all()))[1]), list(zip(*(db.session.query(StandardAndSpe, StandardAndSpe.name).all()))[1])))

    # tool = SelectMultipleField(u'工具', choices=zip(list(zip(*(db.session.query(Tool, Tool.name).all()))[1]), list(zip(*(db.session.query(Tool, Tool.name).all()))[1])), option_widget= widgets.CheckboxInput)

    # organization = SelectMultipleField(u'组织或学校', choices=zip(list(zip(*(db.session.query(Organization, Organization.name).all()))[1]), list(zip(*(db.session.query(Organization, Organization.name).all()))[1])))
    # knowledge = SelectMultipleField(u'知识点', choices=zip(list(zip(*(db.session.query(KnowledgeElement, KnowledgeElement.name).all()))[1]), list(zip(*(db.session.query(KnowledgeElement, KnowledgeElement.name).all()))[1])))

    submit = SubmitField(u'提交')
예제 #6
0
class PhotoForm(Form):
    photo = FileField("上传图片!",
                      validators=[
                          FileRequired(),
                          FileAllowed(['jpg', 'png', 'gif'], '只能传jpg,png,gif')
                      ])
    submit = SubmitField('上传')
예제 #7
0
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?")
예제 #8
0
class ModifyProductForm(Form):
    product_id = IntegerField(validators=[Required(), ])
    name = StringField(validators=[Required(), Length(1, 50), ])
    description = StringField(validators=[Required(), ])
    cat2_id = IntegerField(validators=[Required(), ])
    price = DecimalField(validators=[Required(), ]) 
    img = FileField(validators=[Optional(), ])
예제 #9
0
class CreateCardForm(Form):
    name = TextField('name')
    description = TextAreaField('description')
    holoAllowed = BooleanField(label='Holographic allowed')
    holoAlways = BooleanField(label='Holographic always')
    image = FileField()
    backgroundColor = TextField('color')
예제 #10
0
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')
예제 #11
0
파일: forms.py 프로젝트: weijiayun/Json
class AvatarForm(Form):
    avatar = FileField('avatar',
                       validators=[
                           FileRequired(),
                           FileAllowed(['jpg', 'png'], 'Images only!')
                       ])
    submit = SubmitField()
예제 #12
0
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!')
                       ])
예제 #13
0
class UploadForm(Form):
    upload = FileField('Upload a file:',
                       validators=[
                           FileRequired(),
                           FileAllowed(app.config['ALLOWED_EXTENSIONS'],
                                       "not allowed")
                       ])
    submit = SubmitField("Upload")
예제 #14
0
class PhaseOneForm(Form):
    presentation = FileField('Presentation in PDF Format',
                             validators=[
                                 FileRequired(),
                                 FileAllowed(['pdf'],
                                             'Please upload in PDF format.')
                             ])
    submit = SubmitField("Send")
예제 #15
0
파일: tools.py 프로젝트: next-backend/chiki
class PkgForm(Form):
    version = SelectField('版本', validators=[DataRequired()])
    apk = FileField('应用包')

    def validate_apk(form, field):
        if not field.data:
            raise ValueError('请上传应用文件')
        if not field.data.filename.endswith('.apk'):
            raise ValueError('请上传APK文件')
예제 #16
0
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")
예제 #17
0
파일: forms.py 프로젝트: andreip/SyncOMatic
class UploadForm(Form):
    """Form used for uploading files. This form
       is intended only for validation purposes.
    """
    upload = FileField("Upload your image", validators=[Required()])

    def save_file(self, path):
        filename = secure_filename(self.upload.data.filename)
        self.upload.data.save(os.path.join(path, filename))
예제 #18
0
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!')])
예제 #19
0
파일: form.py 프로젝트: flask-ml/flask-ml
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')
예제 #20
0
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!')])
예제 #21
0
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
예제 #22
0
파일: forms.py 프로젝트: xeonpc/WanMuJia
class SettingsForm(Form):
    logo = FileField(validators=[Image(required=False, message=u'logo不正确')])
    mobile = StringField()
    telephone = StringField(validators=[Length(7, 15, u'电话号码不正确')])
    contact = StringField()
    address = StringField(validators=[Length(1, 30, u'地址不正确')])
    introduction = StringField(validators=[Length(0, 30, u'厂家简介不正确')])
    # area_cn_id = StringField(validators=[AreaValidator(), Length(6, 6)])
    email = StringField()
    brand = StringField()

    logo_url = None

    address_attributes = ('province', 'city', 'district')

    def __init__(self, vendor, *args, **kwargs):
        super(SettingsForm, self).__init__(*args, **kwargs)
        self.email.validators = [Email(model=Vendor, exist_owner=vendor)]

    def show_address(self):
        grades_id = [_.cn_id for _ in current_user.address.area.grade()]
        while len(grades_id) < 3:
            grades_id.append(None)
        for attr, cn_id in zip(self.address_attributes, grades_id):
            setattr(self, attr, cn_id)

    def show_vendor_setting(self, vendor):
        self.telephone.data = vendor.telephone
        self.introduction.data = vendor.introduction
        # self.area_cn_id.data = vendor.address.cn_id
        self.contact.data = vendor.contact
        self.address.data = vendor.address.address
        self.mobile.data = vendor.mobile
        self.logo_url = url_for('static', filename=vendor.logo)
        self.show_address()
        self.email.data = vendor.email
        self.brand.data = vendor.brand

    def update_vendor_setting(self, vendor):
        vendor.introduction = self.introduction.data
        vendor.telephone = self.telephone.data
        vendor.contact = self.contact.data
        vendor.address.address = self.address.data
        # vendor.address.cn_id = self.area_cn_id.data
        if vendor.email != self.email.data:
            vendor.email = self.email.data
            vendor.email_confirmed = False
        if self.logo.data:
            logo, image_hash = save_image(vendor.id, 'vendor', self.logo, self.logo.data.stream)
            vendor.logo = logo
        db.session.add(vendor)
        db.session.add(vendor.address)
        db.session.commit()
예제 #23
0
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!')
                      ])
예제 #24
0
파일: ui.py 프로젝트: xflicsu/immuno
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')
예제 #25
0
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')
예제 #26
0
파일: forms.py 프로젝트: ilmarh/messagetest
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
예제 #27
0
class UserProfileForm(Form):
    name = StringField(
        label=u'이름',
        validators=[validators.data_required(message=u'이름을 입력하여주세요.')],
        description=u'이름을 입력해주세요'
    )
    desc = StringField(
        label=u'자기소개',
        validator=[validators.data_required(message=u'자기소개를 입력하여주세요.')],
        description=u'간략하게 소개해주세요'
    )
    picture = FileField(
        label=u'사진',
        validators=[file_required(message=u'사진을 첨부하여주세요.')],
        description=u'사진을 첨부해주세요.'
    )
예제 #28
0
class CurvesForm(Form):
    """ Form to describe a Curves+ run. """
    num_strands = 4

    # pdbfile = FileField('File', [Required()])
    # pdbid = TextField('PDBid', [Required(), Length(min=4, max=4)])
    pdbfile = FileField('File')
    pdbid = TextField('PDBid')

    strands = FieldList(FormField(StrandForm), min_entries=num_strands)

    fit = BooleanField('Fit')
    circ = BooleanField('Circ')
    line = BooleanField('Line')
    zaxe = BooleanField('Zaxe')
    refo = BooleanField('Refo')
    # test = BooleanField('Test')
    boolean_fields = 'fit circ line zaxe refo'.split()

    viewer = SelectField('3D Viewer', choices=[
        ('jsmol', 'JSmol (slow but fully featured)'),
        ('ngl', 'NGL (fast and simple)'),
        ('none', 'None (output files and plots)')])

    back = TextField('Back',  [Required(), Length(min=1, max=64)])
    wback = FloatField('Wback', [Required()])
    wbase = FloatField('Wbase', [Required()])
    naxlim = IntegerField('Naxlim', [Required()])
    rvfac = FloatField('RVFac', [Required()])

    def validate_pdbfile(self, field):
        pass
        # app.logger.info(
        #     "PDB <"+self.pdbfile.data+"> ID<"+self.pdbid.data+">")
        # if len(self.pdbfile.data) == 0 and len(self.pdbid.data) == 0:
        #     raise ValidationError('Must specify either PDB File of PDBid')

    validate_pdbid = validate_pdbfile

    def validate_strands(self, field):
        """ Accept if subunits are specified for any of the strands."""
        if not reduce(
                lambda x, y: x or y,
                [len(entry.data['nucleotides']) > 0
                 for entry in field.entries]):
            raise ValidationError(
                'Must specify subunits for at least one strand.')
예제 #29
0
파일: forms.py 프로젝트: jayjiahua/project
class CreateProductForm(Form):
    name = StringField(validators=[
        Required(),
        Length(1, 50),
    ])
    description = StringField(validators=[
        Required(),
    ])
    cat2_id = IntegerField(validators=[
        Required(),
    ])
    price = DecimalField(validators=[
        Required(),
    ])
    img = FileField(validators=[
        FileRequired(),
    ])
예제 #30
0
파일: forms.py 프로젝트: xeonpc/WanMuJia
class ItemImageForm(Form):
    item_id = IntegerField()
    file = FileField(validators=[Image(required=True, message=u'商品图片不正确')])

    def validate_item_id(self, field):
        if field.data:
            item = Item.query.get(field.data)
            if not item or item.vendor_id != current_user.id:
                raise ValidationError('wrong id')
        else:
            raise ValidationError('wrong id')

    def add_item_image(self):
        image_path, image_hash = save_image(self.item_id.data, 'item', self.file, self.file.data.stream)
        item_image = ItemImage(self.item_id.data, image_path, image_hash, self.file.data.filename[:30], 999)  # 新上传的图片默认在最后
        db.session.add(item_image)
        db.session.commit()
        return {'hash': item_image.hash, 'url': item_image.url, 'created': item_image.created}
예제 #31
0
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!')])
예제 #32
0
 def __call__(self, **kwargs):
   if 'multiple' not in kwargs and self.multiple:
     kwargs['multiple'] = 'multiple'
   return BaseFileField.__call__(self, **kwargs)