Пример #1
0
    def convert(self, column):
        kwargs = {
            'label': column.info.get('label', column.name),
            'description': column.description,
            'validators': [],
            'default': column.default and column.default.arg
        }
        
        if column.info.get('optional', False):
            kwargs['validators'].append(validators.optional())
        elif not column.nullable:
            kwargs['validators'].append(validators.required())
        
        if hasattr(column.type, 'length') and column.type.length is not None:
            kwargs['validators'].append(validators.length(max=column.type.length))
        
        fname = type(column.type).__name__

        if len(column.foreign_keys) > 0:
            return self.conv_ForeignKey(kwargs, column)

        if fname in self.SIMPLE_CONVERSIONS:
            return self.SIMPLE_CONVERSIONS[fname](**kwargs)
        else:
            mod = getattr(self, 'conv_%s' % fname, None)
            if mod is not None:
                return mod(kwargs, column)
Пример #2
0
def convert_StringProperty(model, prop, kwargs):
    """Returns a form field for a ``db.StringProperty``."""
    if prop._repeated:
        return StringListPropertyField(**kwargs)
    else:
        kwargs['validators'].append(validators.length(max=500))
        return get_TextField(kwargs)
Пример #3
0
def convert_StringProperty(model, prop, kwargs):
    """Returns a form field for a ``db.StringProperty``."""
    if prop.multiline:
        kwargs['validators'].append(validators.length(max=500))
        return f.TextAreaField(**kwargs)
    else:
        return get_TextField(kwargs)
Пример #4
0
def get_TextField(kwargs):
    """
    Returns a ``TextField``, applying the ``db.StringProperty`` length limit
    of 500 bytes.
    """
    kwargs['validators'].append(validators.length(max=500))
    return f.TextField(**kwargs)
Пример #5
0
    def create_form(self, relations=True):
        model = self.model
        class_name = '%sForm' % mixedcase(model._name)
        attrs = {}
        fields = model.fields_get(self.fields)
        defaults = model.default_get(fields.keys())
        for k, v in fields.items():
            type_field = MAPPING_TYPES.get(v.get('type', 'float'))
            if not type_field:
                continue
            override = self._get_form_overrides(k)
            if override:
                type_field = override
            kwargs = {}
            validators = []
            if 'required' in v and v['required']:
                validators.append(wtf_validators.required())
            if 'size' in v:
                validators.append(wtf_validators.length(max=v['size']))
            if k in defaults and defaults[k] is not False:
                kwargs['default'] = defaults[k]
            if v.get('help'):
                kwargs['description'] = v['help']
            if v['type'] == 'selection':
                if v['selection'] and isinstance(v['selection'][0][0], int):
                    kwargs['coerce'] = int
                kwargs['choices'] = v['selection']
            elif v['type'] == 'char' and 'invisible' in v and v['invisible']:
                type_field = PasswordField
            elif v['type'] == 'date':
                kwargs['widget'] = widgets.DatePickerWidget()
            elif v['type'] == 'datetime':
                kwargs['widget'] = widgets.DateTimePickerWidget()
            elif v['type'] in ('many2one', 'one2many'):
                kwargs['coerce'] = coerce_relation
                if v['type'] == 'many2one':
                    kwargs['widget'] = widgets.Select2Widget()
                elif v['type'] == 'one2many':
                    kwargs['widget'] = ListWidget()
                elif v['type'] == 'many2many':
                    kwargs['widget'] = widgets.Select2Widget(multiple=True)

            attrs[k] = type_field(label=v['string'], **kwargs)
        return type(class_name, (BaseForm, ), attrs)
Пример #6
0
    def test_lazy_proxy(self):
        """Tests that the validators support lazy translation strings for messages."""

        class ReallyLazyProxy(object):
            def __unicode__(self):
                raise Exception('Translator function called during form declaration: it should be called at response time.')
            __str__ = __unicode__

        message = ReallyLazyProxy()
        self.assertRaises(Exception, str, message)
        self.assertRaises(Exception, text_type, message)
        self.assertTrue(equal_to('fieldname', message=message))
        self.assertTrue(length(min=1, message=message))
        self.assertTrue(NumberRange(1, 5, message=message))
        self.assertTrue(required(message=message))
        self.assertTrue(regexp('.+', message=message))
        self.assertTrue(email(message=message))
        self.assertTrue(ip_address(message=message))
        self.assertTrue(url(message=message))
Пример #7
0
    def test_length(self):
        field = DummyField('foobar')
        self.assertEqual(length(min=2, max=6)(self.form, field), None)
        self.assertRaises(ValidationError, length(min=7), self.form, field)
        self.assertEqual(length(min=6)(self.form, field), None)
        self.assertRaises(ValidationError, length(max=5), self.form, field)
        self.assertEqual(length(max=6)(self.form, field), None)

        self.assertRaises(AssertionError, length)
        self.assertRaises(AssertionError, length, min=5, max=2)

        # Test new formatting features
        grab = lambda **k: grab_error_message(length(**k), self.form, field)
        self.assertEqual(grab(min=2, max=5, message='%(min)d and %(max)d'), '2 and 5')
        self.assertTrue('at least 8' in grab(min=8))
        self.assertTrue('longer than 5' in grab(max=5))
        self.assertTrue('between 2 and 5' in grab(min=2, max=5))
Пример #8
0
    def test_length(self):
        field = DummyField("foobar")
        self.assertEqual(length(min=2, max=6)(self.form, field), None)
        self.assertRaises(ValidationError, length(min=7), self.form, field)
        self.assertEqual(length(min=6)(self.form, field), None)
        self.assertRaises(ValidationError, length(max=5), self.form, field)
        self.assertEqual(length(max=6)(self.form, field), None)

        self.assertRaises(AssertionError, length)
        self.assertRaises(AssertionError, length, min=5, max=2)

        # Test new formatting features
        grab = lambda **k: grab_error_message(length(**k), self.form, field)
        self.assertEqual(grab(min=2, max=5, message="%(min)d and %(max)d"), "2 and 5")
        self.assert_("at least 8" in grab(min=8))
        self.assert_("longer than 5" in grab(max=5))
        self.assert_("between 2 and 5" in grab(min=2, max=5))
Пример #9
0
    def convert(self, field):
        kwargs = {
            'label': field.verbose_name,
            'description': field.help_text,
            'validators': [],
            'default': field.default,
        }
        if field.blank:
            kwargs['validators'].append(validators.optional())
        if field.max_length is not None and field.max_length > 0:
            kwargs['validators'].append(validators.length(max=field.max_length))

        fname = type(field).__name__

        if field.choices:
            kwargs['choices'] = field.choices
            return f.SelectField(**kwargs)
        elif fname in self.SIMPLE_CONVERSIONS:
            return self.SIMPLE_CONVERSIONS[fname](**kwargs)
        else:
            m = getattr(self, 'conv_%s' % fname, None)
            if m is not None:
                return m(kwargs, field)
Пример #10
0
    def scaffold_form(self):
        """改写form"""
        form_class = super(GiftView, self).scaffold_form()
        delete_attrs(form_class, ("pub", "number", "win_number", "create_time", "intro"))
        form_class.intro = TextAreaField(label=u"奖品介绍", validators=[validators.required(), validators.length(max=256)])

        return form_class
Пример #11
0
class LoginForm(FlaskForm):
    user_id = StringField('user_id',
                          [validators.length(min=1, max=Util.MaxUserIdLength)])
    password = StringField(
        'password', [validators.length(min=1, max=Util.MaxUserPassLength)])
Пример #12
0
class SingleUserForm(FlaskForm):
    name = StringField('Name',
                       validators=[DataRequired(),
                                   length(min=2, max=20)])
    submit = SubmitField('Show Donation')
Пример #13
0
class ReviewForm(Form):
    moviereview = TextAreaField(
        '', [validators.DataRequired(),
             validators.length(min=15)])
Пример #14
0
class RegisterForm(Form):
    name=StringField('Name',[validators.Length(min=1,max=50)])
    username=StringField('Username',[validators.length(min=4,max=25)])
    email=StringField('Email',[validators.Length(min=6,max=50)])
    password=PasswordField('Password',[validators.DataRequired(),validators.EqualTo('confirm',message='Passwords do not match')])
    confirm=PasswordField('Confirm password')
Пример #15
0
    def scaffold_form(self):
        """改写form"""
        form_class = super(TicketView, self).scaffold_form()
        delete_attrs(form_class, ('base_path', 'rel_path', 'pic_name', 'pub', 'create_time', 'intro'))
        form_class.intro = TextAreaField(label=u'优惠券介绍', validators=[validators.required(), validators.length(max=256)])
        form_class.picture = FileField(label=u'优惠券图片', description=u'推荐使用640*288')

        return form_class
Пример #16
0
class SearchForm(Form):
    search = StringField('search', [validators.length(min=2)])
Пример #17
0
class ShopOrderConfirmForm(Form):
    note = TextAreaField('long_desc', [validators.length(max=5000)])
    submit = SubmitField(lazy_gettext('Submit'))
Пример #18
0
class ShopHeaderForm(Form):
    category = SelectField(lazy_gettext('Category'), coerce=int)
    available_only = BooleanField(lazy_gettext('Available item only'))
    search = StringField(lazy_gettext('Search'), [validators.length(min=2)])
Пример #19
0
class AddCategoryForm(Form):
    name_CS = StringField('name_CS', [validators.data_required(),
                                      validators.length(max=50)])
    name_JP = StringField('name_JP', [validators.data_required(),
                                      validators.length(max=50)])
Пример #20
0
class LoginForm(Form):
    nickname = StringField('nickname', [validators.data_required()])
    password = PasswordField('password', [validators.data_required(),
                                          validators.length(min=5, max=30)])
Пример #21
0
class RegisterForm(FlaskForm):
    username = StringField('Username', [DataRequired(), length(max=32)])
    email = StringField('Email', [DataRequired(), length(max=100)])
    password = PasswordField('Password', [DataRequired(), length(max=100)])
Пример #22
0
    def scaffold_form(self):
        """改写form"""
        form_class = super(PubView, self).scaffold_form()
        delete_attrs(form_class, ('access_token_time', 'access_token', 'token', 'appid', 'secret', 'create_time',
                                  'stop_time', 'status', 'base_path', 'rel_path', 'pic_name', 'logo'))
        form_class.user = TextField(label=u'酒吧管理员', validators=[validators.required(), validators.length(max=16)])
        form_class.password = TextField(label=u'管理员密码', validators=[validators.required()])
        form_class.picture = FileField(label=u'酒吧图片',
                                       description=u'为了更好的展示效果,严格使用640 * 288的图片,仅支持png与jpeg(jpg)格式')

        return form_class
Пример #23
0
class NewDistrForm(RedirectForm):
    name = StringField('Name', [validators.required(), validators.length(1, 64)])
    version = StringField('Version', [validators.required(), validators.length(1, 64)])
    release = IntegerField('Release')
Пример #24
0
class new_scenario_form(Form):
    """WTForm for new projects."""

    tst_scenario = TextAreaField('tst_scenario',
                                 validators=[DataRequired(),
                                             length(max=300)])
Пример #25
0
class ArticleForm(Form):
    title = StringField("Makale Başlığı",
                        validators=[validators.length(min=5, max=100)])
    content = TextAreaField("Makale İçeriği",
                            validators=[validators.length(min=10)])
Пример #26
0
class CommentForm(Form):
    input_message = StringField('input_message', [validators.length(min=1)])

    honeypot = HiddenField('', [length_honeypot])
Пример #27
0
class Mine(Form):
    my_text = TextAreaField(
        '', [validators.DataRequired(),
             validators.length(min=15)])
Пример #28
0
class IP_trusted(Form):
    ip = StringField("IP a guardar", [
        validators.length(min=7, max=16, message='IP invalida'),
        validators.DataRequired(message='la Ip es requerida')
    ])
Пример #29
0
 def convert_StringProperty(self, model, prop, kwargs):
     """Returns a form field for a ``ndb.StringProperty``."""
     if prop._repeated:
         return StringListPropertyField(**kwargs)
     kwargs['validators'].append(validators.length(max=500))
     return get_TextField(kwargs)
Пример #30
0
class SearchForm(Form):
    q = StringField(validators=[DataRequired(), length(min=1, max=30)])
    page = IntegerField(validators=[NumberRange(min=1, max=99)], default=1)
Пример #31
0
class postingCForm(Form):
    Body = TextAreaField('Body', [validators.length(min=1, max = 300)])
Пример #32
0
class MakaleFormu(Form):
    title = StringField("Makale Başlığı",
                        validators=[validators.length(5, 100)])
    content = TextAreaField("Makale İçerik",
                            validators=[validators.length(100)])
Пример #33
0

FIELD_MAXLENGTH = 50  # intended to stop maliciously long input
PHONE_MAXLENGTH = 15
TAGS = {'TAG1', 'TAG2', 'TAG3'}

NAME_FIELD_VALIDATORS = [validators.DataRequired(),
                         validators.Length(max=FIELD_MAXLENGTH,
                                           message=_("Field cannot be longer than %(max)d characters.")),
                         validators.regexp(utils.NAME_LASTNAME_REGEXP,
                                           message=_("Name invalid. Use only letters and numbers."))]
EMAIL_FIELD_VALIDATORS = [validators.Length(min=0, max=FIELD_MAXLENGTH, message=_(
                              "Field must be between %(min)d and %(max)d characters long.")),
                          validators.regexp(utils.EMAIL_REGEXP, message=_('Invalid email address.'))]
PHONE_FIELD_VALIDATORS = [validators.length(max=PHONE_MAXLENGTH,
                                            message=_('Phone invalid. Should be less than %(max)s '
                                                      'character long.'))]
WEBSITE_FIELD_VALIDATORS = [validators.Length(max=FIELD_MAXLENGTH,
                                              message=_('Field cannot be longer than %(max)d characters.'))]
NOTES_FIELD_VALIDATORS = [validators.Length(max=65536)]
PASSWORD_FIELD_VALIDATORS = [validators.DataRequired(),
                             validators.Length(max=FIELD_MAXLENGTH, message=_(
                                 "Field cannot be longer than %(max)d characters."))]
TAG_FIELD_VALIDATORS = [validators.Required()]
PRICE_FIELD_VALIDATORS = [validators.NumberRange(min=0.0)]

CARE_TYPE_CHOICES = [('Transfers', 'Transfers'),
                     ('Showering', 'Showering'),
                     ('Dressing', 'Dressing'),
                     ('Personal Care', 'Personal Care'),
                     ('Shopping', 'Shopping'),
Пример #34
0
class ArticleForm(Form):
    title = StringField('Name', [validators.length(min=1, max=200)])
    body = TextAreaField("Body", [validators.length(min=30)])
Пример #35
0
def password_field(label="Password", required=True):
    v = [validators.length(min=6)]
    if required:
        v.append(validators.required())
    return PasswordField(label, v)
Пример #36
0
class LoginForm(Form):
    username = StringField(u'帐号', validators=[Required(), length(6, 64)])
    password = PasswordField(u'密码', validators=[Required()])
    submit = SubmitField(u'登入')
Пример #37
0
from wtforms import fields, validators
from common import form


UserNameField = lambda: fields.TextField(u"Username",
        [validators.required(), validators.regexp('[-a-zA-Z0-9]+'), validators.length(max=256)])


class RegisterForm(form.Form):
    username = UserNameField()
    password = fields.PasswordField(u"Password", [validators.required()])
Пример #38
0
class DeveloperForm(Form):  #
    id = StringField('', [validators.length(min=1)],
                     render_kw={'placeholder': 'Input a product id...'})
Пример #39
0
    def scaffold_form(self):
        """改写form"""
        form_class = super(PubView, self).scaffold_form()
        delete_attrs(form_class, ('access_token_time', 'access_token', 'address', 'tel', 'base_path', 'rel_path',
                                  'pic_name', 'logo', 'create_time'))
        form_class.user = TextField(label=u'酒吧管理员', validators=[validators.required(), validators.length(max=16)])
        form_class.password = TextField(label=u'管理员密码', validators=[validators.required()])

        return form_class
Пример #40
0
class CrearEvento(FlaskForm):
    def nombre_evento(self, field):
        if re.findall("[?/_{$*°}^]", field.data):
            raise validators.ValidationError(
                "Solo los siguientes caracteres especiales estan admitidos (! - # @ . ,)"
            )
        if re.findall("f**k", field.data) or re.findall("n***a", field.data):
            raise validators.ValidationError(
                "El nombre del evento no puede contener malas palabras.")

    def mostrar_datos(self):
        print("Evento: " + str(self.nombreevento.data))
        print("Fecha: " + str(self.fechaevento.data))
        print("Hora: " + str(self.hora.data))
        print("Clasificacion: " + str(self.opciones.data))
        print("Descripcion: " + str(self.descripcion.data))

    def opcional(field):
        field.validators.insert(0, validators.Optional())

    def rangofecha(self, field):
        if field.data < date.today():
            raise validators.ValidationError(
                "Por favor, ingrese una fecha valida")
        # Esta funcion no deja ingresar una fecha en el pasado

    clasificacion = [('Conferencia', 'Conferencia'), ('Curso', 'Curso'),
                     ('Deporte', 'Deporte'), ('Estudio', 'Estudio'),
                     ('E-Sport', 'E-Sport'), ('Festival', 'Festival'),
                     ('Fiesta', 'Fiesta'), ('Musical', 'Musical'),
                     ('Obra', 'Obra'), ('Pasar el rato', 'Pasar el rato'),
                     ('Otro', 'Otro')]

    nombreevento = StringField('Nombre del evento', [
        validators.DataRequired(message="Completar nombre"),
        validators.length(
            min=5,
            max=60,
            message='El nombre del evento debe tener entre 5 y 60 caracteres'),
        nombre_evento
    ])

    fechaevento = DateField('Fecha del Evento', [
        validators.DataRequired(message="Ingrese la fecha de su evento"),
        rangofecha
    ])

    hora = TimeField('Hora de inicio', [
        validators.DataRequired(
            message="Ingrese la hora de inicio de su evento.")
    ])

    lugarevento = StringField('Lugar del evento', [
        validators.DataRequired(
            message="Debe especificar el lugar del evento"),
        validators.length(
            min=5,
            max=60,
            message='El lugar del evento debe tener entre 5 y 60 caracteres')
    ])

    imagen = FileField(validators=[
        FileRequired(),
        FileAllowed(['jpg', 'png'], 'El archivo debe ser una imagen jpg o png')
    ])

    descripcion = TextAreaField('Introduzca una descripcion del evento', [
        validators.DataRequired(message="Por favor ingrese una descripcion"),
        validators.length(
            min=40,
            max=500,
            message=
            'La descripcion del evento debe tener entre 40 y 500 caracteres')
    ])

    opciones = SelectField('Tipo de evento', [], choices=clasificacion)

    submit = SubmitField("Crear evento!")
    actualizar = SubmitField("Actualizar")
Пример #41
0
 def Length(cls, lmin=-1, lmax=-1, message=None):
     ''' Validates the length of a string. '''
     return validators.length(lmin, lmax, message)
Пример #42
0
class LoginForm(FlaskForm):
    login = StringField(
        'login',
        [validators.length(min=1, max=25, message=FieldIsRequiredMessage)])
    password = PasswordField(
        'password', [validators.length(min=1, message=FieldIsRequiredMessage)])
Пример #43
0
 def convert_GenericProperty(self, model, prop, kwargs):
     """Returns a form field for a ``ndb.ListProperty``."""
     kwargs['validators'].append(validators.length(max=500))
     return get_TextField(kwargs)
Пример #44
0
class ResetPasswordRequestForm(FlaskForm):
    email = StringField('Email',
                        validators=[DataRequired(),
                                    length(1, 64),
                                    Email()])
    submit = SubmitField('Send mail')
Пример #45
0
class PostArticleForm(Form):
    title = StringField(u'标题', validators=[Required(), length(6, 64)])
    body = TextAreaField(u'内容')
    category_id = QuerySelectField(u'分类', query_factory=lambda: Category.query.all(), \
            get_pk=lambda a: str(a.id), get_label=lambda a: a.name)
    submit = SubmitField(u'发布')
Пример #46
0
class MessageForm(Form):  # Create Message Form
    body = StringField('', [validators.length(min=1)],
                       render_kw={'autofocus': True})
Пример #47
0
class PostCategoryForm(Form):
    name = StringField(u'分类名', validators=[Required(), length(6, 64)])
    submit = SubmitField(u'发布')
Пример #48
0
 def convert_GenericProperty(self, model, prop, kwargs):
     """Returns a form field for a ``ndb.ListProperty``."""
     kwargs['validators'].append(validators.length(max=500))
     return get_TextField(kwargs)