コード例 #1
0
class BookmarkForm(Form):
    url = URLField("url", validators=[DataRequired(), url()])
    description = StringField("description")

    # overwrite the validate() method of the form class (https://wtforms.readthedocs.io/en/stable/forms.html_)
    # This method is called when we call validate_on_submit() in VF
    def validate(self):
        # Run checks to see how url starts: IF the url does NOT start with http or https, then we add it automatically
        # Ie, if user doesn't enter http or https, we will add it for them BUT they must include the top-level domain  bc that's something the url validtora checks for
        if not self.url.data.startswith("http://") or self.url.data.startswith(
            "https://"
        ):
            self.url.data = "http://" + self.url.data

        # call the validate method on the parent class. This checks all other validtors against the data. If there's an error it retursn False
        if not Form.validate(self):
            return False

        # check if user has entered a description
        # IF not, I set the description to the url, that way the descriotion is NEVER empty
        if not self.description.data:
            self.description.data = self.url.data

        # imp to do this b/c validate() MUST return a bool
        return True
コード例 #2
0
class ProfileCreateForm(Form):
    multipart = True
    next = HiddenField()
    email = EmailField(u'Email', [Required(), Email()])
    name = TextField(u'Name', [Required(), Length(max=100)])
    password = PasswordField(u'Password', [Required(), Length(max=100)])
    password1 = PasswordField(u'Retype-password',
                              [Required(), Length(max=100)])
    # Don't use the same name as model because we are going to use populate_obj().
    avatar_file = FileField(u"Avatar", [Optional()])
    gender_code = RadioField(u"Gender",
                             [AnyOf([str(val) for val in GENDER_TYPE.keys()])],
                             choices=[(str(val), label)
                                      for val, label in GENDER_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()])
    location = TextField(u'Location', [Length(max=64)])
    bio = TextAreaField(u'Bio', [Length(max=1024)])
    submit = SubmitField(u'Save')

    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 validate_password(self, field):
        if field.data != self.password1.data:
            raise ValidationError("The Passwords Don't Match")
コード例 #3
0
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
コード例 #4
0
ファイル: forms.py プロジェクト: paulkarikari/rootio_web
class EditProfileForm(Form):
    multipart = True
    next = HiddenField()
    networks = QuerySelectMultipleField(
        query_factory=lambda: current_user.networks)
    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()])
    gender_code = RadioField(u"Gender",
                             [AnyOf([str(val) for val in GENDER_TYPE.keys()])],
                             choices=[(str(val), label)
                                      for val, label in GENDER_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()])
    location = TextField(u'Location', [Length(max=64)])
    bio = TextAreaField(u'Bio', [Length(max=1024)])
    submit = SubmitField(u'Save')

    def set_networks(self, networks):
        #self.networks.choices = networks
        pass

    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))
コード例 #5
0
ファイル: forms.py プロジェクト: paulkarikari/rootio_web
class ProfileForm(ProfileFormBase):
    multipart = True
    next = HiddenField()
    name = TextField(u'Name', [Required()])
    email = EmailField(u'Email', [Required(), Email()])
    #role_code = RadioField(_("Role")) #, [AnyOf([str(val) for val in USER_ROLE.keys()])], choices=[(str(val), label) for val, label in role_codes().items()])
    # Don't use the same name as model because we are going to use populate_obj().
    avatar_file = FileField(u"Avatar", [Optional()])
    gender_code = RadioField(u"Gender",
                             [AnyOf([str(val) for val in GENDER_TYPE.keys()])],
                             choices=[(str(val), label)
                                      for val, label in GENDER_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()])
    location = TextField(u'Location', [Length(max=64)])
    bio = TextAreaField(u'Bio', [Length(max=1024)])
    submit = SubmitField(u'Save')

    def get_role_codes(self, role_code):
        if role_code == 0:
            roles = USER_ROLE
        elif role_code == 3:
            roles = {k: v for k, v in USER_ROLE.items() if k in ('2', '3')}
        elif role_code == 1:
            roles = USER_ROLE[1:2]
        self.role_code = RadioField(
            _("Role"), [AnyOf([str(val) for val in roles.keys()])],
            choices=[(str(val), label) for val, label in roles.items()])

    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))
コード例 #6
0
ファイル: forms.py プロジェクト: demogloire/kivu
class EdProForm(FlaskForm):
    ed_nom = StringField('Nom',
                         validators=[
                             DataRequired("Completer nom"),
                             Length(min=4,
                                    max=32,
                                    message="Veuillez respecté les caractères")
                         ])
    ed_prix_p = DecimalField('Prix',
                             validators=[DataRequired("Le prix du produit")])
    ed_img_url = URLField('URL')
    resume_android = TextAreaField(
        'Contenu', validators=[DataRequired("Completer le contenu")])
    ed_rech_cate = QuerySelectField(query_factory=rech_cate,
                                    get_label='nom',
                                    allow_blank=False)
    mesure = StringField('Unité de mesure',
                         validators=[
                             DataRequired("Unité de mesure"),
                             Length(min=4,
                                    max=32,
                                    message="Veuillez respecté les caractères")
                         ])
    resume = TextAreaField('Contenu',
                           validators=[DataRequired("Completer le contenu")])
    submit = SubmitField('Produit')
コード例 #7
0
ファイル: forms.py プロジェクト: rontav/rootio_web
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()])
    receive_station_notifications = BooleanField(
        _('Receive Program Notifications'))
    gender_code = RadioField(_("Gender"),
                             [AnyOf([str(val) for val in GENDER_TYPE.keys()])],
                             choices=[(str(val), label)
                                      for val, label in GENDER_TYPE.items()])
    age = IntegerField(_('Age'), [Optional(), NumberRange(AGE_MIN, AGE_MAX)])
    phone = TelField(_('Phone'), [Length(max=64)])
    url = URLField(_('URL'), [Optional(), URL()])
    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)))
コード例 #8
0
ファイル: forms.py プロジェクト: tuckerrc/vwplatform
class ResourceForm(Form):
    """
    Resource contribution form. Info from this is passed to the VW
    adaptor and creates a new model run in the virtual watershed.
    Scientist name is also required, but handled using current_user
    since share blueprint requires login.
    """
    title = StringField(
        'Unique resource title (ex. Dry Creek iSNOBAL '
        'Data)',
        validators=[Required()])

    description = StringField('Describe your new data resource',
                              validators=[Required()])

    keywords = StringField('Keywords, separated by commas',
                           validators=[Required()])

    url = URLField('Resource URL. Leave blank if you will upload to the '
                   'virtual watershed.')

    submit = SubmitField('Share your resource!')

    def reset(self):
        blank_data = MultiDict([('csrf', self.reset_csrf())])
        self.process(blank_data)
コード例 #9
0
ファイル: forms.py プロジェクト: brizow/FlaskBookmarkSite
class BookmarkForm(Form):
    #create fields with more readablility thanks to the jinja macro form
    url = URLField("The URL for your bookmark:",
                   validators=[DataRequired(), url()])
    description = StringField("Add an optional description:")

    #"""This creates a user form for inputting data. This has two fields, url and description"""
    #url = URLField("url", validators=[DataRequired(), url()])
    #description = StringField("description")

    #overrides the default validator
    #if not http:// or https:// then add it to the data.
    def validate(self):
        if not self.url.data.startswith("http://") or\
               self.url.data.startswith("https//"):
            self.url.data = "http://" + self.url.data

        #calls the normal validate class on the parent form. Checks for all other errors.
        if not Form.validate(self):
            return False

        #check whether the user typed a description, if not use the url as the description.
        if not self.description.data:
            self.description.data = self.url.data

        #if everything checks out return true so the validator
        #class knows things are good to go.
        return True
コード例 #10
0
ファイル: forms.py プロジェクト: JsonTyler/FlaskersonUX
class ProjectForm(FlaskForm):
    filepath = StringField('Filepath', validators=[DataRequired()])
    link = URLField('Url', validators=[url()])
    title = StringField('Title', validators=[DataRequired()])
    language = StringField('Technologies', validators=[DataRequired()])
    caption = StringField('Caption', validators=[DataRequired()])
    submit = SubmitField('Upload to Portfolio')
コード例 #11
0
class ReviewForm(FlaskForm):
    author = StringField('Author', validators=[DataRequired()])
    title = StringField('Title', validators=[DataRequired()])
    summary = TextAreaField('Summary', validators=[DataRequired()])
    review = TextAreaField('Review', validators=[DataRequired()])
    image = URLField('Image Url Only')
    ratings = IntegerField('Rating', validators=[DataRequired()])
    add_review = SubmitField('Add Review')
    edit_review = SubmitField('Edit Review')
コード例 #12
0
class VenueForm(FlaskForm):
    name = StringField('name', validators=[DataRequired()])
    city = StringField('city', validators=[DataRequired()])
    state = SelectField('state', validators=[DataRequired()], choices=states)
    address = StringField('address', validators=[DataRequired()])
    phone = StringField('phone',
                        validators=[DataRequired(),
                                    Regexp(r"[0-9]+")])
    image_link = URLField('image_link', validators=[DataRequired(), url()])
    website = URLField('website', validators=[DataRequired(), url()])
    seeking_talent = BooleanField()
    seeking_description = StringField("seeking_description", )
    genres = SelectMultipleField(
        # TODO implement enum restriction
        'genres',
        validators=[DataRequired()],
        choices=genres)
    facebook_link = URLField('facebook_link',
                             validators=[DataRequired(), url()])
    submit = SubmitField('Add Venue')
コード例 #13
0
class ArtistForm(FlaskForm):
    name = StringField('name', validators=[DataRequired()])
    city = StringField('city', validators=[DataRequired()])
    state = SelectField('state', validators=[DataRequired()], choices=states)
    phone = StringField(
        # TODO implement validation logic for state
        'phone',
        validators=[DataRequired(), Regexp(r"[0-9]+")])
    image_link = URLField('image_link', validators=[DataRequired()])
    genres = SelectMultipleField(
        # TODO implement enum restriction
        'genres',
        validators=[DataRequired()],
        choices=genres)
    facebook_link = URLField(
        # TODO implement enum restriction
        'facebook_link',
        validators=[DataRequired(), url()])
    website = URLField("website", validators=[DataRequired()])
    seeking_venue = BooleanField()
    seeking_description = StringField("seeking_description")
    submit = SubmitField('Add Artist')
コード例 #14
0
class ProfileCreateForm(ProfileCreateFormBase):
    multipart = True
    next = HiddenField()
    networks = QuerySelectMultipleField(
        query_factory=lambda: current_user.networks)
    email = EmailField(u'Email', [Required(), Email()])
    name = TextField(u'Name', [Required(), Length(max=100)])
    password = PasswordField(u'Password', [Required(), Length(max=100)])
    password1 = PasswordField(u'Retype-password',
                              [Required(), Length(max=100)])
    role_code = RadioField(_("Role"),
                           [AnyOf([str(val) for val in USER_ROLE.keys()])],
                           choices=[])
    # Don't use the same name as model because we are going to use populate_obj().
    avatar_file = FileField(u"Avatar", [Optional()])
    gender_code = RadioField(u"Gender",
                             [AnyOf([str(val) for val in GENDER_TYPE.keys()])],
                             choices=[(str(val), label)
                                      for val, label in GENDER_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()])
    location = TextField(u'Location', [Length(max=64)])
    bio = TextAreaField(u'Bio', [Length(max=1024)])
    submit = SubmitField(u'Save')

    def get_role_codes(self, role_code):
        if role_code == 0:
            return [(str(k), v) for k, v in USER_ROLE.items()]
        elif role_code == 3:
            return [(str(k), v) for k, v in USER_ROLE.items() if k in (3, 4)]
        elif role_code == 1:
            return [(str(k), v) for k, v in USER_ROLE.items()
                    if k in (1, 2, 3, 4)]

    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 validate_password(self, field):
        if field.data != self.password1.data:
            raise ValidationError("The Passwords Don't Match")

    def validate_name(self, field):
        if User.query.filter_by(name=field.data).first() is not None:
            raise ValidationError(_('This username is already registered'))

    def validate_email(self, field):
        if User.query.filter_by(email=field.data).first() is not None:
            raise ValidationError(_('This email is already registered'))
コード例 #15
0
ファイル: forms.py プロジェクト: robleroble/Virtual_Herbarium
class EditUserForm(FlaskForm):
    """Form to edit user details"""

    username = StringField(
        "Username",
        validators=[
            DataRequired(),
            Length(min=4, message="Username must be at least 4 characters."),
        ],
    )
    bio = TextAreaField("About (Optional)")
    location = StringField("Location (Optional)")
    img_url = URLField("Profile Picture as URL (Optional)",
                       validators=[Optional(), url()])
コード例 #16
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
コード例 #17
0
class AddPetForm(FlaskForm):
    """" Form for Adding pets to the pets data table"""
    name = StringField("Pet's name: ",
                       validators=[InputRequired()])
    species = RadioField("What species of Pet? ",
                         validators=[InputRequired()],
                         choices=[('cat', 'Cat'),
                                  ('dog', 'Dog'),
                                  ('porcupine', 'Porcupine')])
    photo_url = URLField("Photo URL: ",
                         validators=[url(), Optional(strip_whitespace=True)])
    age = IntegerField("How old is the pet? ",
                       validators=[Optional(), NumberRange(min=0, max=30)])
    notes = StringField("Notes: ")
    available = BooleanField("Is this pet available for adoption? ")
コード例 #18
0
class CommentForm(FlaskForm):
    name = StringField('姓名', validators=[DataRequired()])
    email = EmailField('邮箱', validators=[Email()])
    url = URLField('网址', validators=[DataRequired()])
    body = TextAreaField('内容', validators=[DataRequired()])
    replay_id = IntegerField(default=None)
    submit = SubmitField('提交')

    def validate_website(self, field):
        if field.data[:4] != "http" and field.data[:5] != "https":
            raise ValidationError("请输入正确网址")

    def validate_replay_id(self, field):
        if field.data:
            if Comment.query.get(field.data) is None:
                raise ValidationError("回复出错")
コード例 #19
0
class AddPetForm(FlaskForm):
    """Form for adding pets."""

    name = StringField("Pet Name", validators=[InputRequired()])
    species = SelectField("Species",
                          choices=[('cat', 'cat'), ('dog', 'dog'),
                                   ('pcp', 'porcupine')],
                          validators=[InputRequired()])
    photo_url = URLField("Photo URL", validators=[Optional()])
    age = IntegerField("Age (years)",
                       validators=[
                           NumberRange(min=0,
                                       max=30,
                                       message="Age must be between 0 and 30"),
                           Optional()
                       ])
    notes = StringField("Notes", validators=[Optional()])
コード例 #20
0
class SignUpForm(FlaskForm):
    """Form for adding user."""

    username = StringField(
        "Username", validators=[InputRequired(message="Please add Username")])
    email = EmailField("Email",
                       validators=[
                           InputRequired(message="Email required"),
                           Email(message="Invalid !")
                       ])
    password = PasswordField(
        "Password",
        validators=[InputRequired(message="Please create a Password")])
    confirm = PasswordField(
        "Confirm Password",
        validators=[InputRequired(message="Please input the same Password")])
    img_url = URLField("URL(Optional)", validators=[Optional()])
コード例 #21
0
ファイル: forms.py プロジェクト: codeforIATI/validator
class UploadForm(FlaskForm):
    """Upload form."""

    url = URLField(validators=[url()])

    def __init__(self, *args, **kwargs):
        """Create instance."""
        super(UploadForm, self).__init__(*args, **kwargs)
        self.user = None

    def validate(self):
        """Validate the form."""
        initial_validation = super(UploadForm, self).validate()
        if not initial_validation:
            return False

        return True
コード例 #22
0
class WebpageForm(Form):
    website = URLField('Website', description='Website URL to check')

    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False
        try:
            r = requests.get(self.website.data)
            print(r.status_code)
            if r.status_code > 302:
                self.website.errors.append('Website not reachable')
                return False
        except requests.exceptions.ConnectionError:
            self.website.errors.append('Website format unknown')
            return False
        return True
コード例 #23
0
class AddPetForm(FlaskForm):

    name = StringField(
        'Name', validators=[InputRequired(message="Please add pet's name!")])
    species = SelectField('Species',
                          choices=[('cat', 'Cat'), ('dog', 'Dog'),
                                   ('porc', 'Porcupine')],
                          validators=[InputRequired()])
    photo_url = URLField('Image', validators=[Optional()])
    age = IntegerField('Age',
                       validators=[
                           Optional(),
                           NumberRange(
                               min=0,
                               max=30,
                               message='The age should be between 0 and 30')
                       ])
    notes = TextAreaField('Notes', validators=[Optional()])
コード例 #24
0
ファイル: __init__.py プロジェクト: BraindeadCrew/Bookmark-v2
class BookmarkForm(AjaxForm):
    id = HiddenField(u'Id')
    link = URLField(u'Link',
                    validators=[
                        validators.required(),
                        validators.url(),
                    ])
    title = TextField(u'Title', validators=[
        validators.required(),
    ])
    description = TextAreaField(u'Description')
    tags = TextField(u'Tags')
    submit = SubmitField(u'Add')
    edit = SubmitField(u'Edit')

    def __init__(self, formdata=None, *args, **kwargs):
        self.id.data = kwargs.get('id', None)
        super(BookmarkForm, self).__init__(formdata, *args, **kwargs)

    def validate(self):
        rv = Form.validate(self)
        if not rv:
            return False

        _id = self.id.data
        link = self.link.data
        title = self.title.data
        description = self.description.data
        tags = map(lambda x: {'name': x.strip()}, self.tags.data.split(','))

        if _id is None or _id == '' or int(_id) < 1:
            self.bookmark = ItemBookmark(tags=tags,
                                         link=link,
                                         title=title,
                                         description=description)
        else:
            self.bookmark = get_bookmark_by_id(_id)
            if self.bookmark is None:
                abort(404)
            self.bookmark.title = title
            self.bookmark.description = description
            self.bookmark.set_tags(tags)

        return True
コード例 #25
0
class LinkForm(Form):
    url = URLField('url',
                   render_kw={
                       'class': 'form-control',
                       'placeholder': 'Webpage URL',
                       'required': True,
                   },
                   id='url',
                   validators=[DataRequired(), URL()])
    max_sent = IntegerField(
        'max_sent',
        render_kw={
            'class': 'form-control',
            'placeholder': 'Max Sentences',
            'required': True,
        },
        id='max_sent',
        default=10,
        validators=[DataRequired(),
                    NumberRange(min=0, max=100)])
コード例 #26
0
class BookmarkForm(Form):
    def __init__(self, *args, **kwargs):
        Form.__init__(self, *args, **kwargs)

    url = URLField('The URL from 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
コード例 #27
0
class FairDatasetForm(FlaskForm):
    name = StringField("Name", validators=[DataRequired()])
    doi = StringField("DOI (Optional)")
    data_url = URLField("Data Link (Optional)", validators=[URL()])
    date = DateField("Date of publication", validators=[DataRequired()])
    description = TextAreaField("Description", validators=[DataRequired()])
    sci_area = StringField(
        "Scientific Area",
        validators=[DataRequired()],
        render_kw={"autocomplete": "off"},
    )
    references = StringField("References (Optional)", validators=[])
    image = FileField(
        "Dataset Image",
        validators=[
            FileRequired(),
            FileAllowed(["jpg", "png"], "Only JPG and PNG images are allowed"),
        ],
    )
    tags = StringField(
        "Tags",
        validators=[
            DataRequired(),
            Regexp(
                r"^[\w,:_\- ]*$",
                message="Allowed tag characters include "
                "letters spaces and , : _ -",
            ),
        ],
    )

    orcid = StringField(
        "ORCID (Optional)",
        validators=[
            Regexp(
                r"^(\d{4}-?){4}$|^$",
                message="The allowed format is"
                " 0000-0000-0000-0000 or nothing",
            )
        ],
    )
コード例 #28
0
class ProfileForm(Form):
    email = EmailField('Email', [DataRequired(), Email()])
    # Don't use the same name as model because we are going to use populate_obj().
    # avatar_file = FileField("Avatar", [Optional()])
    phone = TelField('Phone', [DataRequired(), Length(max=64)])
    url = URLField('URL', [Optional(), URL()])
    location = StringField('Location', [Optional(), Length(max=64)])
    bio = TextAreaField('Bio', [Optional(), Length(max=1024)],
                        description=BIO_TIP)
    submit = SubmitField('Update profile',
                         render_kw={"class": "btn btn-success"})

    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))
コード例 #29
0
ファイル: forms.py プロジェクト: robleroble/Virtual_Herbarium
class SignupForm(FlaskForm):
    """Form to create a new user"""

    username = StringField(
        "Username",
        validators=[
            DataRequired(),
            Length(min=4, message="Username must be at least 4 characters."),
        ],
    )
    password = PasswordField(
        "Password",
        validators=[
            DataRequired(),
            Length(min=6, message="Password must be at least 6 characters."),
        ],
    )
    bio = TextAreaField("About (Optional)")
    location = StringField("Location (Optional)")
    img_url = URLField("Profile Picture as URL (Optional)",
                       validators=[Optional(), url()])
コード例 #30
0
class ProfileCreateForm(Form):
    user_id = None
    multipart = True
    next = HiddenField()
    networks = QuerySelectMultipleField(
        query_factory=lambda: current_user.networks) # networks = (current_user.name,[Required()])
    email = EmailField(_('Email'), [Required(), Email()])
    name = TextField(_('Name'), [Required(), Length(max=100)])
    password = PasswordField(_('Password'), [Required(), Length(max=100)])
    password1 = PasswordField(_('Retype-password'), [Required(), Length(max=100)])

    # Don't use the same name as model because we are going to use populate_obj().
    avatar_file = FileField(_("Avatar"), [Optional()])
    receive_station_notifications = BooleanField(_('Receive Program Notifications'))
    gender_code = RadioField(_("Gender"), [AnyOf([str(val) for val in GENDER_TYPE.keys()])],
                             choices=[(str(val), label) for val, label in GENDER_TYPE.items()])
    age = IntegerField(_('Age'), [Optional(), NumberRange(AGE_MIN, AGE_MAX)])
    phone = TelField(_('Phone'), [Length(max=64)])
    url = URLField(_('URL'), [Optional(), URL()])
    location = TextField(_('Location'), [Length(max=64)])
    bio = TextAreaField(_('Bio'), [Length(max=1024)])
    submit = SubmitField(_('Save'))

    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 validate_password(self, field):
        if field.data != self.password1.data:
            raise ValidationError(_("The Passwords Don't Match"))

    def validate_name(self, field):
        if User.query.filter(User.name==field.data).filter(User.id != self.user_id).first() is not None:
            raise ValidationError(_('This username is already registered'))

    def validate_email(self, field):
        if User.query.filter(User.email==field.data).filter(User.id != self.user_id).first() is not None:
            raise ValidationError(_('This email is already registered'))