How to use the wtforms.validators function in WTForms

To help you get started, we’ve selected a few WTForms examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github eleweek / WatchPeopleCode / wpc / forms.py View on Github external
raise ValidationError('This email is already in the database.')


class SubscribeForm(Form):
    email = StringField("Email address", [validators.DataRequired(), validators.Email(), validate_email_unique])
    submit_button = SubmitField('Subscribe!')


# TODO: better way
class GLMSubscribeForm(Form):
    email = StringField("Email address", [validators.DataRequired(), validators.Email()])
    submit_button = SubmitField('Subscribe')


class DashboardEmailForm(Form):
    email = StringField("Email address", [validators.DataRequired(), validators.Email()])
    submit_button = SubmitField('Update')

    def prepopulate(self, streamer):
        if streamer.as_subscriber:
            self.email.data = streamer.as_subscriber.email


class DashboardAddVideoForm(Form):
    link = StringField("Youtube link", [validators.DataRequired()])
    submit_button = SubmitField('Add video to the archive')

    def validate_link(form, field):
        ytid = youtube_video_id(field.data)
        if not ytid:
            raise ValidationError("Invalid Youtube URL")
github Code4SA / mma-dexter / dexter / mine.py View on Github external
@roles_accepted('monitor', 'miner')
@client_cache_for(minutes=10)
def mine_people():
    """ All the people that are in the documents covered by this span. """
    form = MineForm(request.args)

    sa = SourceAnalyser(doc_ids=form.document_ids())
    sa.load_people_sources()

    return jsonify({
        'people': [p.json() for p in sa.people.itervalues()]
    })


class MineForm(Form):
    medium_id       = HiddenField('Medium', [validators.Optional()])
    # period to cover, expressed in days since yesterday
    period          = RadioField('Period', [validators.Optional()], choices=[('7', 'last 7 days'), ('30', 'last 30 days'), ('90', 'last 90 days')], default='7')
    source_person_id = TextField('With source', [validators.Optional()])
    # free text search
    q = TextField('Search', [validators.Optional()])

    nature_id = AnalysisNature.ANCHOR_ID

    def __init__(self, *args, **kwargs):
        super(MineForm, self).__init__(*args, **kwargs)
        self.country = current_user.country
        self.yesterday = date.today() - timedelta(days=1)

    @property
    def published_from(self):
        try:
github eucalyptus / eucaconsole / eucaconsole / forms / login.py View on Github external
current_password = wtforms.PasswordField(
        _(u'Current password'), validators=[validators.InputRequired(message=_(u'Password is required'))],
        widget=NGPasswordInput())

    new_password = wtforms.PasswordField(
        _(u'New password'),
        validators=[
            validators.InputRequired(message=_(u'New Password is required')),
            validators.Length(min=6, message=_(u'Password must be more than 6 characters'))
        ],
        widget=NGPasswordInput())

    new_password2 = wtforms.PasswordField(
        _(u'Confirm new password'),
        validators=[
            validators.InputRequired(message=_(u'New Password is required')),
            validators.Length(min=6, message=_(u'Password must be more than 6 characters'))
        ],
        widget=NGPasswordInput())


class EucaLogoutForm(BaseSecureForm):
    pass
github Pagure / pagure / pagure / hooks / pagure_request_hook.py View on Github external
pagure.lib.tasks_services.load_json_commits_to_db.delay(
                name=project.name,
                commits=commits,
                abspath=repodir,
                data_type="pull-request",
                agent=username,
                namespace=project.namespace,
                username=project.user.user if project.is_fork else None,
            )


class PagureRequestsForm(FlaskForm):
    """ Form to configure the pagure hook. """

    active = wtforms.BooleanField("Active", [wtforms.validators.Optional()])


class PagureRequestHook(BaseHook):
    """ Pagure request hook. """

    name = "Pagure requests"
    description = (
        "Pagure specific hook to update pull-requests stored "
        "in the database based on the information pushed in the requests "
        "git repository."
    )
    form = PagureRequestsForm
    db_object = PagureRequestsTable
    backref = "pagure_hook_requests"
    form_fields = ["active"]
    runner = PagureRequestRunner
github Pagure / pagure / pagure / hooks / jenkins_hook.py View on Github external
:raises ConfigNotFound: when no configuration matches
    """
    cfg = SESSION.query(PagureCI).filter(
        service == project_name).all()
    if not cfg:
        raise ConfigNotFound(project_name)
    return cfg


class JenkinsForm(wtf.Form):

    '''Form to configure Jenkins hook'''

    pagure_name = TextField('Name of project in Pagure',
                            [validators.Required(),
                             validators.Length(max=255)])

    jenkins_name = TextField('Name of project in Jenkins',
                             [validators.Required(),
                              validators.Length(max=255)])

    jenkins_url = TextField('Jenkins URL',
                            [validators.Required(),
                             validators.Length(max=255)],
                            default='http://jenkins.fedorainfracloud.org/')

    jenkins_token = TextField('Jenkins token',
                              [validators.Required()])

    active = BooleanField('Active', [validators.Optional()])
github NVIDIA / DIGITS / plugins / data / imageGradients / digitsDataPluginImageGradients / forms.py View on Github external
train_image_count = utils.forms.IntegerField(
        'Train Image count',
        validators=[
            validators.DataRequired(),
            validators.NumberRange(min=1),
        ],
        default=1000,
        tooltip="Number of images to create in training set"
    )

    val_image_count = utils.forms.IntegerField(
        'Validation Image count',
        validators=[
            validators.Optional(),
            validators.NumberRange(min=0),
        ],
        default=250,
        tooltip="Number of images to create in validation set"
    )

    test_image_count = utils.forms.IntegerField(
        'Test Image count',
        validators=[
            validators.Optional(),
            validators.NumberRange(min=0),
        ],
        default=0,
        tooltip="Number of images to create in validation set"
    )

    image_width = wtforms.IntegerField(
github kizniche / Mycodo / mycodo / mycodo_flask / forms / forms_settings.py View on Github external
lazy_gettext('Grid Cell Height (px)'), widget=NumberInput())
    max_amps = DecimalField(
        lazy_gettext('Max Amps'), widget=NumberInput(step='any'))
    output_stats_volts = IntegerField(
        lazy_gettext('Voltage'), widget=NumberInput())
    output_stats_cost = DecimalField(
        lazy_gettext('Cost per kWh'), widget=NumberInput(step='any'))
    output_stats_currency = StringField(lazy_gettext('Currency Unit'))
    output_stats_day_month = StringField(lazy_gettext('Day of Month'))
    output_usage_report_gen = BooleanField(lazy_gettext('Generate Usage/Cost Report'))
    output_usage_report_span = StringField(lazy_gettext('Time Span to Generate'))
    output_usage_report_day = IntegerField(
        lazy_gettext('Day of Week/Month to Generate'), widget=NumberInput())
    output_usage_report_hour = IntegerField(
        lazy_gettext('Hour of Day to Generate'),
        validators=[validators.NumberRange(
            min=0,
            max=23,
            message=lazy_gettext("Hour Options: 0-23")
        )],
        widget=NumberInput()
    )
    stats_opt_out = BooleanField(lazy_gettext('Opt-out of statistics'))
    enable_upgrade_check = BooleanField(lazy_gettext('Check for Updates'))
    net_test_ip = StringField(lazy_gettext('Internet Test IP Address'))
    net_test_port = IntegerField(
        lazy_gettext('Internet Test Port'), widget=NumberInput())
    net_test_timeout = IntegerField(
        lazy_gettext('Internet Test Timeout'), widget=NumberInput())
    Submit = SubmitField(TRANSLATIONS['save']['title'])
github entrepreneur-interet-general / OpenScraper / openscraper / forms.py View on Github external
class SampleForm(Form):
	name = TextField(
			'Username', 
			validators = [ Length(min=4, message="Too short")],
			render_kw  = { "class" : "input" }
	)

	email = PasswordField(
		'Email', 
		validators = [ Length(min=4, message="Not a valid mail address"), Email()], 
		render_kw  = { "class" : "input" }
	)

class EasyForm(Form):
	name 	= TextField('name', validators=[wtforms.validators.DataRequired()], default=u'test')
	email 	= TextField('email', validators=[wtforms.validators.Email(), wtforms.validators.DataRequired()])
	message = TextAreaField('message', validators=[wtforms.validators.DataRequired()])




"""
### SNIPPETS FROM SOLIDATA - based on Flask but still...
github ooclab / remotex / OLD / api / ms / jobx / src / codebase / controllers / spider / forms.py View on Github external
platform = StringField("Platform", [validators.Length(min=2, max=64)])

    title = StringField("Title", [validators.Length(min=2, max=256)])
    body = TextField("Body", [validators.Length(min=2)])
    body_markup = SelectField(
        "Body Markup",
        choices=MARKUP_CHOICES,
        validators=[validators.optional()],
        default="text"
    )

    url = StringField("URL", [validators.Length(min=6)])
    sid = StringField("Source ID", [validators.Length(min=2, max=128)])

    price = IntegerField("Price")
    status = StringField("Status", [validators.Length(max=64)])

    city = FieldList(StringField("City List"))
    category = FieldList(StringField(
        "Category List",
        [validators.Length(max=128)]
    ))
    role = FieldList(StringField(
        "Role List",
        [validators.Length(max=128)]
    ))
    skill = FieldList(StringField(
        "Skill List",
        [validators.Length(max=128)]
    ))

    # TODO: 校验 UTC string
github inveniosoftware / invenio / invenio / modules / oauth2server / forms.py View on Github external
# Forms
#
class ClientFormBase(model_form_factory(InvenioBaseForm)):

    """Base class for Client form."""

    class Meta:
        model = Client
        exclude = [
            'client_secret',
            'is_internal',
        ]
        strip_string_fields = True
        field_args = dict(
            website=dict(
                validators=[validators.DataRequired(), validators.URL()],
                widget=widgets.TextInput(),
            ),
        )


class ClientForm(ClientFormBase):

    """Client form."""

    # Trick to make redirect_uris render in the bottom of the form.
    redirect_uris = RedirectURIField(
        label="Redirect URIs (one per line)",
        description="One redirect URI per line. This is your applications"
                    " authorization callback URLs. HTTPS must be used for all "
                    "hosts except localhost (for testing purposes).",
        validators=[RedirectURIValidator(), validators.DataRequired()],