コード例 #1
0
ファイル: forms.py プロジェクト: jphire/flask-blog
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))
コード例 #2
0
ファイル: forms.py プロジェクト: yashika5/Flask_thermos
class BookmarkForm(Form):
    url = URLField('The URL for your bookmark:',
                   validators=[DataRequired(), url()])
    description = StringField('Add an optional description:')
    tags = StringField(
        'Tags',
        validators=[
            Regexp(r'^[A-Za-z0-9, ]*$',
                   message="Tags can only contain letters and numbers")
        ])

    def validate(self):
        if not (self.url.data.startswith("http://")
                or self.url.data.startswith("https://")):
            self.url.data = "http://" + self.url.data

        if not Form.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        #filter out empty and duplicate tag names
        stripped = [t.strip() for t in self.tags.data.split(',')]
        not_empty = [tag for tag in stripped if tag]
        tagset = set(not_empty)
        self.tags.data = ",".join(tagset)

        return True
コード例 #3
0
class BookmarkForm(Form):
    # customized validation function
    def validate_len(form, field):
        if len(field.data) > 15 or len(field.data) < 1:
            raise ValidationError('The length of description should be [1,15]')

    # using html5 url field
    url = URLField('New URL: ', validators=[DataRequired(), url()])
    description = StringField('Description: ', [validate_len])

    # customized the validation function
    # override the validate function
    # this will be called when validate_on_submit
    def validate(self):

        if not self.url.data.startswith("http://") or \
            self.url.data.startswith("https://"):
            self.url.data = "http://" + self.url.data

        # original validation check
        if not Form.validate(self):
            return False

        # make description not empty
        if not self.description.data:
            self.description.data = self.url.data

        return True
コード例 #4
0
class RegisterForm(Form):
    username = StringField('Username: '******'^[A-Z,a-z0-9_]{3,}$')
                           ])
    name = StringField('Full name: ',
                       validators=[DataRequired(),
                                   Length(4, 65)])
    email = StringField('Email', validators=[DataRequired(), Email()])
    picture = URLField('URL for your photo: ',
                       validators=[DataRequired(), url()])
    password = PasswordField(
        'Password: '******'confirmPassword')])
    confirmPassword = PasswordField('Confirm Password',
                                    validators=[DataRequired()])
    submit = SubmitField('Log In')

    def validate_email(self, email_field):
        if User.query.filter_by(email=email_field.data).first():
            raise ValidationError(
                'An account with this email has already been created.')

    def validate_user(self, name_field):
        if User.query.filter_by(name=name_field.data).first():
            raise ValidationError('This username is taken')
コード例 #5
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.')
    )
コード例 #6
0
class PostForm(Form):
    """ Form to submit a Post
        TODO: Put a note in about Markdown formatting?
    """
    title = TextField('Title', description='', validators=[required()])
    url = URLField('URL', description='', validators=[url(), optional()])
    text = TextAreaField('Text', description='', validators=[])
    kind = TextField('Kind')
コード例 #7
0
ファイル: account.py プロジェクト: fossix/fossix_site
class OpenID_LoginForm(Form):
    next = HiddenField()
    openid = URLField("OpenID",
                      validators=[
                          required("You didn't enter a OpenID URL"),
                          url("OpenID must be a valid URL")
                      ])

    submit = SubmitField("Login")
コード例 #8
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'))
コード例 #9
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)])
コード例 #10
0
class BookmarkForm(Form):
    url = URLField('url', validators=[DataRequired(), url()])
    description = StringField('description')

    def validate(self):
        if not self.url.data.startswith("http://") or \
                self.url.data.startswith("https://"):
            self.url.data = "http://" + self.url.data
        if not Form.validate(self):
            return False
        if not self.description.data:
            self.description.data = self.url.data

        return True
コード例 #11
0
class Create_star_form(Form):
    """ Generate form for creating a star """
    # Choices of the creator field need to be set before displaying the form
    # TODO: Validate creator selection
    creator = SelectField('Creator', validators=[
        Required(),
    ])
    text = TextField('Content',
                     validators=[
                         Required(),
                     ],
                     widget=widgets.TextArea())
    picture = FileField('Picture')
    link = URLField('Link', validators=[])
コード例 #12
0
ファイル: forms.py プロジェクト: yuruidong/PYtypecho
class OptionGeneralForm(Form):
    title = StringField(u"网站标题", description=u"站点的名称将显示在网页的标题处.")
    url = URLField(u"网站地址", description=u"站点地址主要用于生成内容的永久链接.")
    description = StringField(u"网站描述", description=u"站点描述将显示在网页代码的头部.")
    keyword = StringField(u"关键字", description=u"请以半角逗号\",\"分割多个关键字.")
    duoshuo_name = StringField(u"多说short_name", description=u"请填写你的多说short_name")
    submit = SubmitField(u"保存设置")

    def __init__(self, option=None):
        super(OptionGeneralForm, self).__init__()
        if option:
            self.title.data = option.title
            self.url.data = option.url
            self.keyword.data = option.keyword
            self.description.data = option.description
            self.duoshuo_name.data = option.duoshuo_name
コード例 #13
0
class BookmarkForm(Form):
    url = URLField("The URL for your bookmark:",
                   validators=[DataRequired(), url()])
    description = StringField("Add an optional description:")

    def validate(self):
        if not (self.url.data.startswith("http://")
                or self.url.data.startswith("https://")):
            self.url.data = "http://" + self.url.data

        if not Form.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        return True
コード例 #14
0
ファイル: forms.py プロジェクト: azelenovsky/thermos
class BookmarkForm(Form):
    url = URLField(
        'url', validators=[DataRequired(), url()]
    )  #Actual Fields WTForms will use these attributes to generate fields instances
    description = StringField('description')

    def validate(self):
        if not (self.url.data.startswith("http://") or\
                self.url.data.startswith("https://")):
            self.url.data = "http://" + self.url.data

        if not Form.validate(self):
            return False

        if not self.description.data:
            self.description.data = self.url.data

        return True
コード例 #15
0
class EditProfileForm(Form):

    name = TextField(_('Full name'), validators=[Required()])

    twitter = TextField(_('Twitter'))
    facebook = TextField(_('Facebook'))

    website = URLField(_('Website or blog'))

    email = EmailField(_('Email'))

    location = TextField(_('Location'))

    hireable = SelectField(_('Hireable'),
                           choices=[(0, _("No")), (1, _('Yes'))],
                           coerce=int,
                           description=_("Are you free to hire ?"))

    bio = TextAreaField(_('Bio'))

    submit = SubmitField(_('Update profile'))
コード例 #16
0
class BookmarkForm(Form):
    '''Create an Form Object to Validate
        Arguments:
            Form - Form Objetct - BookmarkForm
        Validator:
            url:
                has value - DataRequired()
                valid url input - url()
            description:
    '''
    nm_url = URLField('The URL for your bookmark:',
                      validators=[DataRequired(message='Input an URL'),
                                  url()])
    nm_description = StringField('Add an optional description:')
    tags = StringField('Tags:',
                       validators=[
                           Regexp(
                               '^[A-Za-z0-9, ]*$',
                               message='Tags consit of letters and numbers.')
                       ])

    def validate(self):
        if not (self.nm_url.data.startswith('https://')
                or self.nm_url.data.startswith('http://')):
            self.nm_url.data = "http://" + self.nm_url.data

        if not Form.validate(self):
            return False

        if not self.nm_description.data:
            self.nm_description.data = self.nm_url.data

        #filter our empty and duplicate tag names
        stripped = [t.strip()
                    for t in self.tags.data.split(',')]  #retira os espaços
        not_empty = [tag for tag in stripped if tag]  #retira os vazios
        tagset = set(not_empty)  #retira os duplicados
        self.tags.data = ','.join(tagset)

        return True
コード例 #17
0
class ProfileForm(Form):
    username = StringField('username', validators=validators['username'])
    location = StringField('area', validators=[Length(max=64)])
    website = URLField('Homepage', validators=[Length(max=256)])
    introduction = TextAreaField('Introduction', validators=[Length(max=1024)])
コード例 #18
0
class InputURLform(Form):
    url = URLField('URL of source page to be changed', validators=[url()])
コード例 #19
0
ファイル: forms.py プロジェクト: duthfox/pywiki
class ProfileForm(Form):
    username = StringField('呢称*', validators=validators['username'])
    location = StringField('所在地区', validators=[Length(max=64)])
    website = URLField('个人主页', validators=[Length(max=256)])
    introduction = TextAreaField('个人简介', validators=[Length(max=1024)])
コード例 #20
0
ファイル: forms.py プロジェクト: JamesDavidCarr/devfun
class PostForm(Form):
    title = TextField('Title', [Length(min=1, max=80)])
    url = URLField(validators=[url()])

    def __init__(self, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)
コード例 #21
0
class BookmarkForm(Form):
    url = URLField('enter your URL', validators=[DataRequired(), url()])
    description = StringField('description')
    '''def validate(self):
コード例 #22
0
ファイル: forms.py プロジェクト: sanggiChoi/flask-bluebone
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'))
コード例 #23
0
class BookmarkForm(Form):
    url = URLField('url', validators=[DataRequired(), url()])
    description = StringField('description')
コード例 #24
0
ファイル: forms.py プロジェクト: thuvh/manekineko
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()
コード例 #25
0
class LinkForm(Form):
	url = URLField(validators=[required(), url()])
	delete_after_usage = BooleanField('delete_after_usage', default=False)