Beispiel #1
0
class ProfileForm(Form):
    multipart = True
    next = HiddenField()
    email = EmailField(u'Email', [Required(), Email()])
    # Don't use the same name as model because we are going to use populate_obj().
    avatar_file = FileField(u"Avatar", [Optional()])
    sex_code = RadioField(u"Sex",
                          [AnyOf([str(val) for val in SEX_TYPE.keys()])],
                          choices=[(str(val), label)
                                   for val, label in SEX_TYPE.items()])
    age = IntegerField(u'Age', [Optional(), NumberRange(AGE_MIN, AGE_MAX)])
    phone = TelField(u'Phone', [Length(max=64)])
    url = URLField(u'URL', [Optional(), URL()])
    deposit = DecimalField(
        u'Deposit',
        [Optional(), NumberRange(DEPOSIT_MIN, DEPOSIT_MAX)])
    location = TextField(u'Location', [Length(max=64)])
    bio = TextAreaField(u'Bio', [Length(max=1024)])
    submit = SubmitField(u'Save')

    def validate_name(form, field):
        user = User.get_by_id(current_user.id)
        if not user.check_name(field.data):
            raise ValidationError("Please pick another name.")

    def validate_avatar_file(form, field):
        if field.data and not allowed_file(field.data.filename):
            raise ValidationError("Please upload files with extensions: %s" %
                                  "/".join(ALLOWED_AVATAR_EXTENSIONS))
Beispiel #2
0
class SettingForm(BaseForm):
    screen_name = TextField(_('Display Name'), validators=[Length(max=80)])
    website = URLField(_('Website'), validators=[URL(), Optional()])
    city = TextField(_('City'), description=_('Where are you living'))
    description = TextAreaField(_('Description'),
                                validators=[Optional(),
                                            Length(max=400)],
                                description=_('Markdown is supported.'))
Beispiel #3
0
class ProfileForm(Form):
    next = HiddenField()
    name = TextField(
            label = _("Username"),
            validators = [
                Required(),
                Length(USERNAME_LEN_MIN, USERNAME_LEN_MAX),
                ],
            description = u"Combination of letters/digits/underscore, at least %s characters." % USERNAME_LEN_MIN,
            )
    email = EmailField(
            label = _('Email'), 
            validators = [Email()],
            )
    created_time = DateField(
            label = _('Created time'),
            )
    role_id = RadioField(
            label = "Role",
            validators = [AnyOf([str(val) for val in USER_ROLE.keys()])],
            choices = [(str(val), label) for val, label in USER_ROLE.items()],
            )
    status_id = RadioField(
            label = "Status",
            validators = [AnyOf([str(val) for val in USER_STATUS.keys()])],
            choices = [(str(val), label) for val, label in USER_STATUS.items()],
            )
    real_name = TextField(
            label = _('Real name'),
            validators = [
                Length(REALNAME_LEN_MIN, REALNAME_LEN_MAX),
                ]
            )
    age = IntegerField(
            label = _('Age'), 
            validators = [NumberRange(AGE_MIN, AGE_MAX)],
            )
    phone = TelField(
            label = _('Phone'), 
            )
    url = URLField(
            label = _('URL'), 
            validators = [URL()],
            )
    deposit = DecimalField(
            label = _('Deposit'), 
            validators = [NumberRange(DEPOSIT_MIN, DEPOSIT_MAX)],
            )
    location = TextField(
            label = _('Location'), 
            validators = [Length(max=50)]
            )
    bio = TextAreaField(
            label = _('Bio'), 
            validators = [Length(max=1024)]
            )
    submit = SubmitField(_('Save'))
Beispiel #4
0
class URLForm(Form):
    url = TextField(
        'URL',
        [Required(), Length(max=255), URL()], widget=XXLargeTextInput())
    slug = TextField('Slug',
                     [Optional(), Length(max=30),
                      Regexp(RE_SLUG)],
                     widget=TextInput())
    submit = SubmitField('shorten')
Beispiel #5
0
class HotelForm(Form):
    id = TextField("Id", validators=[Length(min=36, max=36)])
    name = TextField("Name", validators=[Length(max=40)])
    butterfly_url = URLField("Butterfly URL", validators=[URL()])
    butterfly_user = TextField("Butterfly user", validators=[Length(max=10)])
    butterfly_token = TextField("Butterfly token", validators=[Length(40)])
    shorthand = TextField("Shorthand", validators=[Length(max=5)])
    cups_address = TextField("Cups IP address", validators=[Length(max=200)])
    cups_password = TextField("Cups password", validators=[Length(max=200)])
Beispiel #6
0
class BookmarkForm(Form):
    url = TextField("URL", [Required(), URL(require_tld=True)])
    title = TextField("Title", [Required()])
    description = TextAreaField('Description')
    tags = SelectMultipleField('Tags')
    public = BooleanField('Public?')

    def __init__(self, *args, **kwargs):
        super(BookmarkForm, self).__init__(*args, **kwargs)
        self.tags.choices = [(t.name, t.name) for t in Tag.query.all()]
Beispiel #7
0
def optional_url(form, field):
    """
    Validate URL only if present.
    """
    if not field.data:
        return
    else:
        if ':' not in field.data:
            field.data = 'http://' + field.data
        validator = URL(
            message="Invalid URL. URLs must begin with http:// or https://")
        return validator(form, field)
Beispiel #8
0
class HttpAddForm(AddForm):

    base_url = TextField("Base URL",    validators = [Required(), URL(False) ])
    login    = TextField("Login",    validators = [Required() ])
    password = PasswordField("Password",    validators = [])
    extension = TextField("Extension",    validators = [], description = "If required, provide an extension (e.g., .php) to the HTTP API")
    mode = SelectField("Mode",  choices=[('json', 'Pure JSON requests and responses'), ('json+form', 'JSON for responses, HTML forms for requests')], default = "json")

    def __init__(self, add_or_edit, *args, **kwargs):
        super(HttpAddForm, self).__init__(*args, **kwargs)

    @staticmethod
    def process_configuration(old_configuration, new_configuration):
        return new_configuration
Beispiel #9
0
class AddForm(AddForm):

    remote_login = TextField("Login", validators=[Required()])
    password = PasswordField("Password")

    base_url = TextField("Base URL", validators=[Required(), URL()])

    mappings = TextField("Mappings", validators=[Required()], default="{}")

    def __init__(self, add_or_edit, *args, **kwargs):
        super(AddForm, self).__init__(*args, **kwargs)
        self.add_or_edit = add_or_edit

    @staticmethod
    def process_configuration(old_configuration, new_configuration):
        old_configuration_dict = json.loads(old_configuration)
        new_configuration_dict = json.loads(new_configuration)
        if new_configuration_dict.get('password', '') == '':
            new_configuration_dict['password'] = old_configuration_dict.get(
                'password', '')
        return json.dumps(new_configuration_dict)

    def validate_password(form, field):
        if form.add_or_edit and field.data == '':
            raise ValidationError("This field is required.")

    def validate_mappings(form, field):
        try:
            content = json.loads(field.data)
        except:
            raise ValidationError("Invalid json content")

        if not isinstance(content, dict):
            raise ValidationError("Dictionary expected")

        for key in content:
            if not isinstance(key, basestring):
                raise ValidationError("Keys must be strings")

            if '@' not in key:
                raise ValidationError(
                    "Key format: experiment_name@experiment_category ")

            value = content[key]
            if not isinstance(value, basestring):
                raise ValidationError("Values must be strings")

            if '@' not in value:
                raise ValidationError(
                    "Value format: experiment_name@experiment_category ")
Beispiel #10
0
class VirtualAddForm(AddForm):

    web = TextField("Web", validators=[Required(), URL()])
    web_name = TextField("Web name", validators=[Required()])
    height = TextField("Height")
    translation_url = TextField(
        "Translations URL",
        description=
        "List of translations for this lab in a particular JSON format, if available"
    )

    def __init__(self, add_or_edit, *args, **kwargs):
        super(VirtualAddForm, self).__init__(*args, **kwargs)

    @staticmethod
    def process_configuration(old_configuration, new_configuration):
        return new_configuration
Beispiel #11
0
class SettingsForm(Form):
    username = TextField(
        u'用户名',
        validators=[Required(),
                    Length(min=4, max=32),
                    Regexp(re_username)])
    #nickname = TextField(u'昵称', validators=[Optional(), Length(max=32)])
    city = TextField(u'城市', validators=[Optional(), Length(max=40)])
    province = TextField(u'省份', validators=[Optional(), Length(max=40)])
    birthday = DateField(u'出生年月日',
                         validators=[Optional()],
                         widget=DatePickerWidget(),
                         default=datetime.date(1990, 1, 1))
    blog = TextField(u'博客', validators=[Optional(), URL(), Length(max=100)])
    descp = TextAreaField(u'个人介绍', validators=[Optional(), Length(max=500)])
    signature = TextAreaField(u'签名', validators=[Optional(), Length(max=200)])
    realname = TextField(u'真实姓名', validators=[Optional(), Length(max=80)])
    idcard = TextField(u'身份证', validators=[Optional(), Length(max=32)])
Beispiel #12
0
class Deal_Form(Form):
    title = TextField("title",
                      validators=[Required(message='This is required')])
    categories = SelectField(u'Group',
                            choices=[(category.title(), category) for category in cats])
    location = TextField("location",
                         validators=[
                            Length(max=300, message="location can't be longer than 300 characters"),
                            URL(message="Doesn't look like a valid link. Valid links should start with http://")
                         ])
    description = TextAreaField('description',
                                 validators=[
                                    Length(max=5000, message="Description can't be longer than 5000 characters")
                                 ])
    submit = SubmitField("Submit")

    def __init__(self, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)

    def validate(self):
        rv = Form.validate(self)
        if not rv:
            # Hack - if the self.location.data is "", the URL validator
            # will raise an invalid URL error. But the length validator should
            # raise no errors since "" has length < 300.
            #
            # Therefore, if self.location.data is None, we can assume that
            # there is only 1 location error, and the error is invalid URL.
            # Since we want to allow the user to NOT enter a URL, we will
            # to pop the invalid URL error from self.location.error
            if self.location.data == "":
                self.location.errors.pop()
            if len(self.title.data) > 128:
                num = len(self.title.data) - 128
                message = "This is too long by {num} characters"\
                          .format(num=num)
                self.title.errors.append(message)
            if self.title.errors or self.categories.errors or \
                self.location.errors or self.description.errors:
                return False
        return True
Beispiel #13
0
class ProfileForm(Form):
    multipart = True
    next = HiddenField()
    email = EmailField(_('Email'), [Required(), Email()])
    # Don't use the same name as model because we are going to use populate_obj().
    avatar_file = FileField(_("Avatar"), [Optional()])
    sex_code = RadioField(_("Sex"),
                          [AnyOf([str(val) for val in SEX_TYPE.keys()])],
                          choices=[(str(val), label)
                                   for val, label in SEX_TYPE.items()])
    age = IntegerField(_('Age'), [Optional(), NumberRange(AGE_MIN, AGE_MAX)])
    phone = TelField(_('Phone'), [Length(max=64)])
    url = URLField(_('URL'), [Optional(), URL()])
    deposit = DecimalField(
        _('Deposit'),
        [Optional(), NumberRange(DEPOSIT_MIN, DEPOSIT_MAX)])
    location = TextField(_('Location'), [Length(max=64)])
    bio = TextAreaField(_('Bio'), [Length(max=1024)])
    submit = SubmitField(_('Save'))

    def validate_name(form, field):
        user = User.get_by_id(current_user.id)
        if not user.check_name(field.data):
            raise ValidationError(_("Please pick another name."))

    def validate_avatar_file(form, field):
        if field.data and not allowed_file(field.data.filename):
            raise ValidationError(
                _("Please upload files with extensions:") +
                " %s" % "/".join(ALLOWED_AVATAR_EXTENSIONS))

    def create_profile(self, request, user):

        if self.avatar_file.data:
            upload_file = request.files[self.avatar_file.name]
            if upload_file and allowed_file(upload_file.filename):
                # Don't trust any input, we use a random string as filename.
                # or use secure_filename:
                # http://flask.pocoo.org/docs/patterns/fileuploads/

                user_upload_dir = os.path.join(
                    current_app.config['UPLOAD_FOLDER'], "user_%s" % user.id)
                current_app.logger.debug(user_upload_dir)

                make_dir(user_upload_dir)
                root, ext = os.path.splitext(upload_file.filename)
                today = datetime.now().strftime('_%Y-%m-%d')
                # Hash file content as filename.
                hash_filename = hashlib.sha1(
                    upload_file.read()).hexdigest() + "_" + today + ext
                user.avatar = hash_filename

                avatar_ab_path = os.path.join(user_upload_dir, user.avatar)
                # Reset file curso since we used read()
                upload_file.seek(0)
                upload_file.save(avatar_ab_path)

        self.populate_obj(user)
        self.populate_obj(user.user_detail)

        db.session.add(user)
        db.session.commit()
Beispiel #14
0
class EntryAddScreenshot(Form):
    url = TextField("URL", validators=[Required(), URL()])
    caption = TextField("Caption", validators=[Required()])
Beispiel #15
0
class ProfileForm(Form):
    first_name = TextField(
        label=_('First Name'),
        validators=[
            Length(
                min=FIRSTNAME_LEN_MIN,
                max=FIRSTNAME_LEN_MAX,
                ),
            ],
        )
    last_name = TextField(
        label=_('Last Name'),
        validators=[
            Length(
                min=LASTNAME_LEN_MIN,
                max=LASTNAME_LEN_MAX,
                ),
            ],
        )
    username = TextField(
        label=_('Username'),
        validators=[
            Required(),
            Length(
                min=USERNAME_LEN_MIN,
                max=USERNAME_LEN_MAX,
                ),
            ],
        description=_(u"Combination of letters/digits/underscore, at least %s characters." % USERNAME_LEN_MIN),
        )
    email = EmailField(
        label=_('Email'),
        validators=[Email(
            message=_("Doesn't look like a valid email.")
            )],
        )
    """ TODO role_id = RadioField(
        label=_('Role'),
        validators=[
            validators.AnyOf(USER_ROLE.keys())
            ],
        choices=USER_ROLE.items(),
        )"""
    gender = SelectField(
        label=_('Gender'),
        choices=[
            ('male', 'Male'),
            ('female', 'Female')
            ]
        )
    dob = DateField(
        label=_('Date of Birth')
        )
    phone = TelField(
        label=_('Phone Number'),
        )
    bio = TextAreaField(
        label=_('Biography'),
        validators=[
            Length(
                max=1024,
                ),
            ]
        )
    url = URLField(
        label=_('Website'),
        validators=[
            URL(),
            ],
        )
    submit = SubmitField(_('Save'))
Beispiel #16
0
class NewLinkForm(Form):
    url = TextField('URL', validators=[Required(), URL()])
    title = TextField('Title', validators=[Required()])
    description = TextAreaField('Description', validators=[Required()])
    image = FileField('Image', validators=[Required()])