Exemple #1
0
class SampleFilterForm(FlaskForm):
    """Form for querying Sample documents."""

    # location in the ontology
    kinetics = fields.RadioField(choices=('', 'static', 'dynamic'))

    spatial_dim = fields.RadioField(choices=('', '2d', '3d'))
Exemple #2
0
class SampleForm(FlaskForm):
    """Form for creating a new Samples document."""

    session = fields.IntegerField('Session', validators=[validators.required()])
    position = fields.IntegerField(
        'Sample Position/FOV', validators=[validators.required()]
    )

    time_step = fields.StringField('Time Step', validators=[validators.Length(0, 255)])
    z_step = fields.StringField('Z Step', validators=[validators.Length(0, 255)])

    specimen = fields.StringField(
        'Specimen Name', validators=[validators.Length(0, 1000)]
    )

    # imaging parameters (embedded document fields)
    imaging_params = fields.FormField(ImagingParametersForm)

    # dimensions (embedded document fields)
    dimensions = fields.FormField(DimensionsForm)

    # modality (embedded document fields)
    modality = fields.FormField(ModalityInformationForm)

    # location in the ontology
    kinetics = fields.RadioField(
        choices=('static', 'dynamic'), validators=[validators.required()]
    )
    spatial_dim = fields.RadioField(
        choices=('2d', '3d'), validators=[validators.required()]
    )
class MergeNamespaceForm(FlaskForm):
    """Builds a form for merging namespace files"""
    file = FileField(
        'BEL Namespace Files',
        render_kw={'multiple': True},
        validators=[
            DataRequired(),
            FileAllowed(['belns'],
                        'Only files with the *.belns extension are allowed')
        ])
    name = fields.StringField('Name', validators=[DataRequired()])
    keyword = fields.StringField('Keyword', validators=[DataRequired()])
    description = fields.StringField('Description',
                                     validators=[DataRequired()])
    species = fields.StringField('Species Taxonomy Identifiers',
                                 validators=[DataRequired()],
                                 default='9606')
    domain = fields.RadioField('Domain',
                               choices=[(x, x)
                                        for x in sorted(NAMESPACE_DOMAIN_TYPES)
                                        ])
    citation = fields.StringField('Citation Name', validators=[DataRequired()])
    licenses = fields.RadioField(
        'License',
        choices=[('CC BY 4.0', 'Add the CC BY 4.0 license'),
                 ('Other/Proprietary', 'Add an "Other/Proprietary" license')],
        default='CC BY 4.0')
    submit = fields.SubmitField('Merge')
Exemple #4
0
class PrescreenForm(Form):
    household_size = fields.IntegerField(_('What is your household size?'),
                                         validators=[])
    household_income = fields.IntegerField(
        _('What is your monthly household income?'), validators=[])
    has_health_insurance = fields.RadioField(
        _('Do you have health insurance?'),
        choices=CONSTANTS.YNN_NONULL_CHOICES,
        default="",
    )
    eligible_for_medicaid = fields.RadioField(
        _('Are you eligible for Medicare/Medicaid?'),
        choices=CONSTANTS.YNN_NONULL_CHOICES,
        default="",
    )
Exemple #5
0
class Page(Topic):
    title = fields.TextField(
        'Title', validators=[validators.InputRequired(), available_page_title])
    comments_disable = fields.RadioField(
        'Is disable comments',
        choices=[('enable', 'enable'), ('disable', 'disable')],
        validators=[validators.InputRequired()])
Exemple #6
0
class Form_dang_ky(FlaskForm):
    ho_ten = fields.StringField('Họ tên:', [validators.required()])
    email = fields.StringField('Email:', [validators.required()])
    ten_dang_nhap = fields.StringField('Tên đăng nhập:',
                                       [validators.required()])
    mat_khau = fields.PasswordField('Mật khẩu:', [validators.required()])
    gioi_tinh = fields.RadioField('Giới tính:',
                                  choices=[('M', 'Nam'), ('F', 'Nữ')])
    ngay_sinh = fields.StringField('Ngày sinh:', [validators.required()])
    dia_chi = fields.StringField('Địa chỉ:', [validators.required()])
    dien_thoai = fields.StringField('Số điện thoại', [validators.required()])

    def validate_ten_dang_nhap(self, ten_dang_nhap):
        if dbSession.query(Nguoi_dung).filter_by(
                ten_dang_nhap=self.ten_dang_nhap.data).count() > 0:
            raise validators.ValidationError('Tên đăng nhập đã được sử dụng!')

    def tao_khach_hang(self):
        user = dbSession.query(Nguoi_dung).filter_by(
            ten_dang_nhap=self.ten_dang_nhap.data).first()
        customer = Khach_hang()
        customer.ma_nguoi_dung = user.ma_nguoi_dung
        customer.ten_khach_hang = self.ho_ten.data
        customer.gioi_tinh = self.gioi_tinh.data
        customer.ngay_sinh = tao_chuoi_ngay(self.ngay_sinh.data)
        customer.dia_chi = self.dia_chi.data
        customer.dien_thoai = self.dien_thoai.data
        dbSession.add(customer)
        dbSession.commit()
        return
Exemple #7
0
class TemplateWizardSingleRowForm(Form):
    row_height = fields.IntegerField('row height', default='100')
    column_count = fields.RadioField('Row columns',
                                     choices=((1, 1), (2, 2), (3, 3), (4, 4),
                                              (5, 5)))
    row_count = fields.HiddenField()
    current_row = fields.HiddenField()
Exemple #8
0
class RegistrationForm(FlaskForm):
    username = StringField(
        label =u'用户名',
        validators = [
        validators.DataRequired(message='用户名不能为空'),
        validators.length(min=4, max=16, message='用户名长度必须大于%(min)d且小于%(max)d')]
    )
    nickname = StringField(
        label =u'昵称',
        validators = [
        validators.DataRequired(message='昵称不能为空'),
        validators.length(min=4, max=32, message='昵称长度必须大于%(min)d且小于%(max)d')]
        )
    email = StringField(label='电子邮箱', 
        validators=[
            validators.DataRequired(message='邮箱不能为空.'),
            validators.Email(message='邮箱格式错误')
         ],
        widget=widgets.TextInput(input_type='email'),
        render_kw={'class': 'form-control'}
    )

    password = PasswordField(
        label=u'密码',
        validators=[
        validators.DataRequired(message=u'密码不能为空'),
        validators.length(min=6, message=u'密码必须大于%(min)d位')
        ],
        widget=widgets.PasswordInput())

    password2 = PasswordField(
        label=u'重复密码',
        validators=[
            validators.DataRequired(message=u'重复密码不能为空.'),
            validators.EqualTo('password',message=u'两次密码不一致')
        ]
        )
   
    gender = fields.RadioField(
        label=u'性别',
        choices=(
            (1,u'男'),
            (0,u'女'),
        ),
        coerce=int,  #限制是int类型的
        render_kw={'class': 'form-control'}
    )

    submit = SubmitField(u'注册')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('该用户名已经被注册!')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('该邮箱已经被注册.')
Exemple #9
0
 class TestForm(Form):
     test = fields.RadioField('test',
                              choices=(
                                  ('val', 'label'),
                                  ('val2', 'label2'),
                                  ('val3', 'label3'),
                                  ('val4', 'label4'),
                              ))
Exemple #10
0
class ScreeningResultForm(Form):
    eligible_yn = fields.RadioField(
        _('Is this patient eligible for care at your organization?'),
        choices=CONSTANTS.YN_NONULL_CHOICES,
        default="",
    )
    sliding_scale_id = fields.SelectField(_('Sliding Scale'), default="")
    notes = fields.TextAreaField(
        _('Notes'), [Optional(), validators.Length(max=1000)])
    submit = fields.SubmitField(_('Submit'))
Exemple #11
0
 class RegisterForm(RSAPasswordForm):
     realname = fields.StringField(
         '姓名',
         description='输入真实姓名',
         validators=[validators.Required(),
                     PinyinLength(min=2)])
     gender = fields.RadioField('性别',
                                choices=[('male', '男'), ('female', '女')],
                                validators=[validators.Required()])
     introduction = fields.TextAreaField('介绍',
                                         description='简短地写点什么介绍下自己吧',
                                         validators=[validators.Required()])
Exemple #12
0
    class ChangeProfilePictureForm(flask_wtf.FlaskForm):
        choices = [('none', 'Ingen')]
        default = None

        for pic in user.profile_pictures:
            if pic == user.profile_picture:
                default = str(pic.id)

            choices.append((str(pic.id), pic.filename))

        profile_picture = fields.RadioField(choices=choices,
                                            default=default or 'none')
class BoilerplateForm(FlaskForm):
    """Builds a form for generating BEL script templates"""
    name = fields.StringField('Document Name', validators=[DataRequired()])
    description = fields.StringField('Document Description',
                                     validators=[DataRequired()])
    pmids = fields.StringField('PubMed Identifiers, separated by commas')
    entrez_ids = fields.StringField('Entrez Identifiers, separated by commas')
    licenses = fields.RadioField(
        'License',
        choices=[('CC BY 4.0', 'Add the CC BY 4.0 license'),
                 ('Other/Proprietary', 'Add an "Other/Proprietary" license')],
        default='CC BY 4.0')
    submit = fields.SubmitField('Generate')
class ValidateNamespaceForm(FlaskForm):
    """Builds a form for validating a namespace"""
    file = FileField(
        'BEL Namespace File',
        validators=[
            DataRequired(),
            FileAllowed(['belns'],
                        'Only files with the *.belns extension are allowed')
        ])
    search_type = fields.RadioField('Search Type',
                                    choices=[('search', 'Search'),
                                             ('suggest', 'Suggest')],
                                    default='search')
    submit = fields.SubmitField('Validate')
class AutosqliForm(FlaskForm):
    test_url = fields.StringField(

        label="TEST URL:",
        validators=[
            validators.DataRequired(message='URL不能为空'),
            validators.URL(require_tld=False, message='url不正确')
        ],
        widget = widgets.TextInput(),
        render_kw={
            "class": "form-control",
            "placeholder": "请输入URL",
            "required": "",
            "autofocus": ""
        }
    )

    request_method = fields.RadioField(

        label="请求方法",
        validators=[
            validators.DataRequired(message='请选择请求方法'),
        ],
        choices=[('get', "GET"),('post','POST')],
        default='post'
    )

    request_params = fields.TextAreaField(
        label='请求参数',
        validators=[
            validators.DataRequired(message='请求参数不能为空')

        ],
        widget=widgets.TextArea(),
        render_kw={
            'class':'form-control',
            'required':'',
            'rows':6
        }
    )

    ignore_params = fields.StringField(
        label='忽略注入字段',
        widget=widgets.TextInput(),
        render_kw={
                'class':'form-control',
                'placeholder':'输入不要检测的字段名'
        }
    )
Exemple #16
0
    class ChangeProfilePictureForm(flask_wtf.FlaskForm):
        choices = [('none', _l('Ingen'))]
        default = None

        pictures = (models.ProfilePicture.query.filter(
            models.ProfilePicture.user_id.is_(user.id)).order_by(
                models.ProfilePicture.timestamp.desc()))
        for pic in pictures:
            if pic == user.profile_picture:
                default = str(pic.id)

            choices.append((str(pic.id), pic.filename))

        profile_picture = fields.RadioField(choices=choices,
                                            default=default or 'none')
Exemple #17
0
class UppersForm(FlaskForm):
    name = fields.StringField(label="Name this Upper", validators=[Required()])
    brand = fields.StringField(label='Brand', validators=[Required()])
    style = fields.SelectField(label='Style', validators=[Required()])
    size = fields.SelectField(label='Size', validators=[Required()])
    year = fields.IntegerField(label='Year Obtained - optional')
    pattern = fields.SelectField(label='Pattern', validators=[Required()])
    color1 = fields.SelectField(label='Color (Primary)',
                                validators=[Required()])
    color2 = fields.SelectField(label='Color (Secondary) - optional')
    color3 = fields.SelectField(label='Color (Accent) - optional')
    fit = fields.SelectField(label='Fit', validators=[Required()])
    material = fields.SelectField(label='Material / Fabric',
                                  validators=[Required()])
    stretch = fields.RadioField(label='Stretch', default="no")
Exemple #18
0
class AddButtonForm(Form):
    name = fields.StringField('button id',validators=[validators.InputRequired()])
    size = fields.SelectField('button size',choices=(
                                        ('xs','x-sm'),('s','small'),
                                        ('m','med'),('l','lrg'),('xl','x-lg')
                                        ))
    color = fields.SelectField('Button color',choices=(
                                        ('blue','blue'),('red','red'),('grey','grey'),
                                        ('green','green'),('yellow','yellow'),('light-blue','light-blue')
                                        ))
    text = fields.StringField('Button text',validators=[validators.InputRequired()])
    icon = fields.SelectField('Button icon',choices=icon_choices.items())
    icon_library = fields.HiddenField('icon_library')
    type = fields.RadioField('Button type',choices=(('submit','submit'),('button','button'),('link','link')))
    link_href = fields.StringField('link url, can be endpoint or uri')
Exemple #19
0
    def convert(self, model, field, field_args):
        kwargs = {
            "label": getattr(field, "verbose_name", field.name),
            "description": getattr(field, "help_text", None) or "",
            "validators": getattr(field, "validators", None) or [],
            "filters": getattr(field, "filters", None) or [],
            "default": field.default,
        }
        if field_args:
            kwargs.update(field_args)

        if kwargs["validators"]:
            # Create a copy of the list since we will be modifying it.
            kwargs["validators"] = list(kwargs["validators"])

        if field.required:
            kwargs["validators"].append(validators.InputRequired())
        else:
            kwargs["validators"].append(validators.Optional())

        ftype = type(field).__name__

        if field.choices:
            kwargs["choices"] = field.choices

            if ftype in self.converters:
                kwargs["coerce"] = self.coerce(ftype)
            multiple_field = kwargs.pop("multiple", False)
            radio_field = kwargs.pop("radio", False)
            if multiple_field:
                return f.SelectMultipleField(**kwargs)
            if radio_field:
                return f.RadioField(**kwargs)
            return f.SelectField(**kwargs)

        ftype = type(field).__name__

        if hasattr(field, "to_form_field"):
            return field.to_form_field(model, kwargs)

        if hasattr(field, "field") and type(field.field) == ReferenceField:
            kwargs["label_modifier"] = getattr(
                model, field.name + "_label_modifier", None
            )

        if ftype in self.converters:
            return self.converters[ftype](model, field, kwargs)
Exemple #20
0
    def convert(self, model, field, field_args):
        kwargs = {
            'label': getattr(field, 'verbose_name', field.name),
            'description': getattr(field, 'help_text', None) or '',
            'validators': getattr(field, 'validators', None) or [],
            'filters': getattr(field, 'filters', None) or [],
            'default': field.default,
        }
        if field_args:
            kwargs.update(field_args)

        if kwargs['validators']:
            # Create a copy of the list since we will be modifying it.
            kwargs['validators'] = list(kwargs['validators'])

        if field.required:
            kwargs['validators'].append(validators.InputRequired())
        else:
            kwargs['validators'].append(validators.Optional())

        ftype = type(field).__name__

        if field.choices:
            kwargs['choices'] = field.choices

            if ftype in self.converters:
                kwargs["coerce"] = self.coerce(ftype)
            multiple_field = kwargs.pop('multiple', False)
            radio_field = kwargs.pop('radio', False)
            if multiple_field:
                return f.SelectMultipleField(**kwargs)
            if radio_field:
                return f.RadioField(**kwargs)
            return f.SelectField(**kwargs)

        ftype = type(field).__name__

        if hasattr(field, 'to_form_field'):
            return field.to_form_field(model, kwargs)

        override = self._get_field_override(field.name)
        if override:
            return override(**kwargs)

        if ftype in self.converters:
            return self.converters[ftype](model, field, kwargs)
Exemple #21
0
    def convert(self, model, field, field_args):
        kwargs = {
            'label': getattr(field, 'verbose_name', field.name),
            'description': getattr(field, 'help_text', ''),
            'validators': getattr(field, 'validators', []),
            'filters': getattr(field, 'filters', []),
            'default': field.default,
            'render_kw': getattr(field, 'render_kw', {}),
        }

        if field_args:
            kwargs.update(field_args)

        kwargs = self.__update_kwargs(field, kwargs)

        ftype = type(field).__name__

        if getattr(field, "queryset", None):
            return ModelSelectField(model=field.queryset, **kwargs)

        if field.choices:
            kwargs['choices'] = field.choices

            if ftype in self.converters:
                kwargs["coerce"] = self.coerce(ftype)
            multiple_field = kwargs.pop('multiple', False)
            radio_field = kwargs.pop('radio', False)
            if multiple_field:
                return f.SelectMultipleField(**kwargs)
            if radio_field:
                return f.RadioField(**kwargs)
            return f.SelectField(**kwargs)

        ftype = type(field).__name__

        if hasattr(field, 'to_form_field'):
            return field.to_form_field(model, kwargs)

        if ftype in self.converters:
            return self.converters[ftype](model, field, kwargs)
Exemple #22
0
class SeedSubgraphForm(FlaskForm):
    """Builds the form for seeding by subgraph"""
    node_list = HiddenField('Nodes')
    seed_method = fields.RadioField(
        'Expansion Method',
        choices=[
            (SEED_TYPE_INDUCTION, 'Induce a subgraph over the given nodes'),
            (SEED_TYPE_NEIGHBORS,
             'Induce a subgraph over the given nodes and expand to their first neighbors'
             ),
            (SEED_TYPE_DOUBLE_NEIGHBORS,
             'Induce a subgraph over the given nodes and expand to their second neighbors'
             ),
            (SEED_TYPE_PATHS,
             'Induce a subgraph over the nodes in all shortest paths between the given nodes'
             ),
            (SEED_TYPE_UPSTREAM, 'Generate an upstream candidate mechanism'),
            (SEED_TYPE_DOWNSTREAM,
             'Generate a downstream candidate mechanism'),
        ],
        default=SEED_TYPE_INDUCTION)
    filter_pathologies = BooleanField('Filter pathology nodes', default=False)
    submit_subgraph = fields.SubmitField('Submit Subgraph')
Exemple #23
0
class CreateGridForm(Form):
    row_count = fields.RadioField('row count',choices=((1,1),(2,2),(3,3)),validators=[validators.InputRequired()])
    row_heights = fields.FormField(HeightFields)
Exemple #24
0
class TemplateWizardRowCountForm(Form):
    row_count = fields.RadioField('row count',choices=((1,1),(2,2),(3,3)),validators=[validators.InputRequired()])
Exemple #25
0
class SearchForm(FlaskForm):

    image = FileField('Image', [FileRequired()])
    rows = fields.IntegerField('Rows', default=20)
    format = fields.RadioField('Format',
                               choices=[('json', 'json'), ('html', 'html')])
Exemple #26
0
class OneMonthFeedbackForm(FlaskForm):
    not_needed = 'We only need this if we didn\'t collect this during the survey.'
    numbers_only = 'Only use digits and (optionally) a decimal point, no other punctuation or symbols.'
    recaptcha = RecaptchaField()
    householders_name = fields.StringField(
        'Householder\'s name*', validators=[DataRequired(),
                                            Length(max=50)])
    address = fields.StringField('Address*',
                                 validators=[DataRequired(),
                                             Length(max=100)])
    #annual_gas_kwh = fields.DecimalField('Annual consumption (kWh)',
    #                                     validators=[Optional()])
    #annual_gas_estimated = fields.BooleanField('(tick for yes) Is the value based on estimated use?',
    #                                           validators=[Optional()])
    #annual_gas_start_date = fields.DateField('Start date (dd/mm/yyyy)',
    #                                         format='%d/%m/%Y',
    #                                         validators=[Optional(),
    #                                         validate_date],
    #                                         widget=DatePickerWidget())
    #annual_gas_end_date = fields.DateField('End date (dd/mm/yyyy)',
    #                                       format='%d/%m/%Y',
    #                                       validators=[Optional(),
    #                                       validate_date],
    #                                       widget=DatePickerWidget())
    #annual_elec_kwh = fields.DecimalField('Annual consumption (kWh)',
    #                                      validators=[Optional()])
    #annual_elec_estimated = fields.BooleanField('(tick for yes) Is the value based on estimated use?',
    #                                            validators=[Optional()])
    #annual_elec_start_date = fields.DateField('Start date (dd/mm/yyyy)',
    #                                          format='%d/%m/%Y',
    #                                          validators=[Optional(),
    #                                          validate_date],
    #                                          widget=DatePickerWidget())
    #annual_elec_end_date = fields.DateField('End date (dd/mm/yyyy)',
    #                                        format='%d/%m/%Y',
    #                                        validators=[Optional(),
    #                                        validate_date],
    #                                        widget=DatePickerWidget())
    #annual_solid_spend = fields.DecimalField('Annual spend on solid fuels (£)',
    #                                         validators=[Optional()])
    #renewable_contrib_kwh = fields.DecimalField('Annual contribution from renewable generation (kWh)',
    #                                            validators=[Optional()])
    any_completed_actions = fields.BooleanField(
        '(tick for yes) Have you already taken action to improve the thermal efficiency of your home?',
        validators=[Optional()])
    completed_actions = fields.TextAreaField(
        'If so, then what have you done? And have you done the work yourself or has it been done professionally?',
        validators=[RequiredIf('any_completed_actions')])
    any_planned_work = fields.BooleanField(
        '(tick for yes) Are you planning to do remedial work in the next few years?',
        validators=[Optional()])
    planned_actions = fields.TextAreaField(
        'If so, then what are you planning?',
        description=
        'This can be anything from draught proofing to installing external wall insulation.',
        validators=[RequiredIf('any_planned_work')])
    any_wellbeing_improvement = fields.BooleanField(
        '(tick for yes) Have the actions you\'ve taken made your house feel warmer?',
        validators=[Optional()])
    wellbeing_improvement = fields.TextAreaField(
        'If so, then how? (Even if perhaps you haven\'t saved money on your bills.)',
        validators=[RequiredIf('any_wellbeing_improvement')])
    any_behaviour_change = fields.BooleanField(
        '(tick for yes) Has your behaviour changed as a result of your survey?',
        validators=[Optional()])
    behaviour_temperature = fields.TextAreaField(
        'How has the period and temperature you use the heating for changed? (if at all)',
        validators=[RequiredIf('any_behaviour_change')])
    behaviour_space = fields.TextAreaField(
        'How do you use space in your home differently? (if at all)',
        validators=[RequiredIf('any_behaviour_change')])
    behaviour_changes = fields.TextAreaField(
        'In what other ways has your behaviour changed after the survey?',
        validators=[RequiredIf('any_behaviour_change')])
    choices_1_to_5 = [choice(str(x)) for x in range(1, 6)]
    satisfaction_1to5 = fields.RadioField(
        'How satisified were you with the survey overall? (1: least, to 5: most)*',
        widget=OneToFiveWidget(),
        choices=choices_1_to_5,
        validators=[DataRequired()])
    survey_video_1to5 = fields.RadioField(
        'How useful have you find the survey video? (1: not at all, to 5: very)*',
        widget=OneToFiveWidget(),
        choices=choices_1_to_5,
        validators=[DataRequired()])
    surveyor_conduct_1to5 = fields.RadioField(
        'How was the conduct of the surveyor? (1: poor, to 5: excellent)*',
        widget=OneToFiveWidget(),
        choices=choices_1_to_5,
        validators=[DataRequired()])
    survey_value_1to5 = fields.RadioField(
        'Was the survey good value for money? (1: disagree, to 5: agree)*',
        widget=OneToFiveWidget(),
        choices=choices_1_to_5,
        validators=[DataRequired()])
    recommend_1to5 = fields.RadioField(
        'Are you likely to recommend the survey to a friend or neighbour? (1: unlikely, to 5: definitely)*',
        widget=OneToFiveWidget(),
        choices=choices_1_to_5,
        validators=[DataRequired()])
    feedback = fields.TextAreaField(
        'Do you have any feedback?',
        description='We would like to hear what you think about:' +
        ' the organisation of the survey,' +
        ' the conduct of the Energy Tracers,' +
        ' the results of the survey and suggested remedies,' +
        ' the overall value for money of the survey,' +
        ' your overall satisfaction,' +
        ' and anything else at all you would like to let us know.',
        validators=[Optional()])
Exemple #27
0
class SearchForm(form.Form):
    value = fields.StringField()
    radio = fields.RadioField(choices=[('first_name', 'Имя'),
                                       ('last_name', 'Фамилия')],
                              default='first_name')
Exemple #28
0
class RegistrationForm(form.Form):
    room_type = fields.RadioField('Тип комнаты',
                                  choices=[('place', 'Место в комнате'),
                                           ('room', 'Отдельную комнату'),
                                           ('family', 'Семейную комнату')],
                                  default='place')
    reason = fields.TextAreaField('Причина')

    first_name = fields.StringField('Имя', validators=[validators.required()])
    last_name = fields.StringField('Фамилия',
                                   validators=[validators.required()])
    middle_name = fields.StringField('Отчество',
                                     validators=[validators.required()])
    birthday = fields.DateField('Дата рождения',
                                validators=[validators.required()])
    department = fields.StringField('Факультет')
    specialty = fields.StringField('Специальность')
    group = fields.IntegerField('Группа')
    work = fields.StringField('Место работы и должность')
    s_passport = fields.StringField('Серия паспорта',
                                    validators=[validators.required()])
    n_passport = fields.StringField('Номер паспорта',
                                    validators=[validators.required()])
    d_passport = fields.DateField('Дата выдачи',
                                  validators=[validators.required()])
    k_passport = fields.StringField('Кем выдан',
                                    validators=[validators.required()])
    phone_number = fields.StringField('Контактные номера телефонов',
                                      validators=[validators.required()])
    email = fields.StringField('Электронная почта')

    lived_radio = fields.RadioField('Жил ли раньше в общежитиии',
                                    choices=[('lived', 'Раньше жил'),
                                             ('nolived', 'Не жил')],
                                    default='nolived')
    lived_hostel = fields.StringField('В общежитии')
    lived_room = fields.StringField('В комнате')

    form_of_education = fields.RadioField('Форма обучения',
                                          choices=[('b', 'Бюджет'),
                                                   ('k', 'Контракт')],
                                          default='b')

    family_radio = fields.RadioField('Семейный студент?',
                                     choices=[('y', 'Да'), ('n', 'Нет'),
                                              ('o', 'Ничего из перечисленного')
                                              ],
                                     default='o')
    father = fields.StringField('Отец')
    father_work = fields.StringField('Место работы')
    mother = fields.StringField('Мать')
    mother_work = fields.StringField('Место работы')
    brothers_sisters = fields.TextAreaField(
        'Братья и сестры до 16 (указать возраст)')
    parents_street = fields.StringField('Улица')
    parents_home = fields.StringField('Дом')
    parents_apartment = fields.StringField('Квартира')
    parents_settlement = fields.StringField('Город/село')
    parents_district = fields.StringField('Район')
    parents_region = fields.StringField('Область')
    parents_index = fields.StringField('Индекс')
    parents_landline_phone = fields.StringField('Стационарный телефон')
    parents_mobile_phone = fields.StringField('Мобильный телефон')

    husband_wife = fields.StringField('Муж/жена')
    husband_wife_work = fields.StringField('Место работы')
    husband_wife_birthday = fields.DateField(
        'Дата рождения', validators=[validators.Optional()])
    husband_wife_s_passport = fields.StringField('Серия паспорта')
    husband_wife_n_passport = fields.StringField('Номер паспорта')
    husband_wife_d_passport = fields.DateField(
        'Дата выдачи', validators=[validators.Optional()])
    husband_wife_k_passport = fields.StringField('Кем выдан')
    husband_wife_form_of_education = fields.RadioField(
        'Форма обучения (для студентов ХГУ)',
        choices=[('b', 'Бюджет'), ('k', 'Контракт')],
        default='b')
    husband_wife_lived = fields.RadioField('Жил ли раньше в общежитиии',
                                           choices=[('lived', 'Раньше жил'),
                                                    ('nolived', 'Не жил')],
                                           default='nolived')
    husband_wife_lived_hostel = fields.StringField('В общежитии')
    husband_wife_lived_room = fields.StringField('В комнате')
    childrens = fields.TextAreaField('Дети(с указанием даты рождения)')
    children_live = fields.RadioField('Ребёнок будет жить в общежитии',
                                      choices=[('y', 'Да'), ('n', 'Нет')],
                                      default='n')
Exemple #29
0
    def convert(self, model, field, field_args):
        # Check if it is overridden field
        if isinstance(field, FieldPlaceholder):
            return form.recreate_field(field.field)

        kwargs = {
            'label': self._get_label(field, field_args),
            'description': getattr(field, 'help_text', ''),
            'validators': [],
            'filters': [],
            'default': field.default,
            # '_translations': babel
        }

        if field_args:
            kwargs.update(field_args)

        if kwargs['validators']:
            # Create a copy of the list since we will be modifying it.
            kwargs['validators'] = list(kwargs['validators'])

        if field.required:
            kwargs['validators'].append(validators.InputRequired())
        elif not isinstance(field, ListField):
            kwargs['validators'].append(validators.Optional())

        if field.unique and not field.unique_with:
            kwargs['validators'].append(Unique(model, field.name))

        if field.unique_with:
            # print field.unique_with, '<<<<<<<<<<<', field.unique
            kwargs['validators'].append(
                UniqueWith(model, field.name, field.unique_with))

        ftype = type(field).__name__
        override = self._get_field_override(field.name)

        # Check choices
        form_choices = getattr(self.view, 'form_choices', None)
        #
        # if mapper.class_ == self.view.model and form_choices:
        #     choices = form_choices.get(prop.key)
        #     if choices:
        #         return form.Select2Field(
        #             choices=choices,
        #             allow_blank=column.nullable,
        #             **kwargs
        #         )

        choices = field.choices
        if form_choices and field.name in form_choices:
            choices = form_choices[field.name]

        if choices:
            kwargs['choices'] = list(self._convert_choices(field.choices))
            if ftype in self.converters:
                kwargs["coerce"] = self.coerce(ftype)
            if kwargs.pop('radio', False):
                return wtf_fields.RadioField(**kwargs)

            if not override:
                if kwargs.pop('multiple', False):
                    return wtf_fields.SelectMultipleField(**kwargs)
                return wtf_fields.SelectField(**kwargs)

        if hasattr(field, 'to_form_field'):
            return field.to_form_field(model, kwargs)

        if override:
            return override(**kwargs)

        if ftype in self.converters:
            return self.converters[ftype](model, field, kwargs)
Exemple #30
0
class DemoForm(form.Form):
    name = fields.TextField(validators=[validators.DataRequired()])
    description = fields.TextAreaField(validators=[validators.DataRequired()])
    sex = fields.SelectField(
        validators=[validators.DataRequired()],
        choices=(
            ("", "Please Select.."),
            ("Male", "Male"),
            ("Female", "Female"),
            ("Other", "Other"),
        ),
        widget=admin_widgets.Select(),
    )
    password = fields.PasswordField(
        validators=[validators.DataRequired()],
        widget=admin_widgets.PasswordInput(),
    )
    tags = admin_fields.TagsField(
        default=[]
    )
    options = fields.SelectMultipleField(
        validators=[validators.DataRequired()],
        choices=(
            ("One", "One"),
            ("Two", "Two"),
            ("Three", "Three"),
            ("Four", "Four"),
            ("Five", "Five"),
            ("Six", "Six"),
            ("Seven", "Seven"),
            ("Eight", "Eight"),
            ("Nine", "Nine"),
            ("Ten", "Ten"),
        ),
        widget=admin_widgets.HorizontalSelect(),
    )
    choices = fields.SelectMultipleField(
        validators=[validators.DataRequired()],
        choices=(
            ("One", "One"),
            ("Two", "Two"),
            ("Three", "Three"),
            ("Four", "Four"),
            ("Five", "Five"),
        ),
        widget=widgets.ListWidget(prefix_label=False),
        option_widget=admin_widgets.CheckboxInput(),
    )
    choice = fields.RadioField(
        validators=[validators.DataRequired()],
        choices=(
            ("One", "One"),
            ("Two", "Two"),
            ("Three", "Three"),
            ("Four", "Four"),
            ("Five", "Five"),
        ),
        option_widget=admin_widgets.RadioInput(),
    )
    agree = fields.BooleanField(
        validators=[validators.DataRequired()],
        widget=admin_widgets.CheckboxInput(),
    )