How to use WTForms - 10 common examples

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 wtforms / wtforms / tests / test_validators.py View on Github external
def test_bad_ip6address_raises(address, dummy_form, dummy_field):
    adr = ip_address()
    dummy_field.data = address
    with pytest.raises(ValidationError):
        adr(dummy_form, dummy_field)
github kvesteri / wtforms-alchemy / tests / test_weekdays_field.py View on Github external
def init_form(self, **kwargs):
        class TestForm(Form):
            test_field = WeekDaysField(**kwargs)
        return TestForm
github kvesteri / wtforms-components / tests / fields / test_color_field.py View on Github external
def init_form(self, **kwargs):
        class TestForm(Form):
            color = ColorField(**kwargs)

        self.form_class = TestForm
        return self.form_class
github wtforms / wtforms / tests / ext_sqlalchemy.py View on Github external
def test_convert_basic(self):
        self.assertRaises(TypeError, model_form, None)
        self.assertRaises(ModelConversionError, model_form, self.Course)
        form_class = model_form(self.Course, exclude=['students'])
        form = form_class()
        self.assertEqual(len(list(form)), 7)
        assert isinstance(form.cost, fields.DecimalField)
        assert isinstance(form.has_prereqs, fields.BooleanField)
        assert isinstance(form.started, fields.DateTimeField)
github LogicJake / WebMonitor / app / main / forms / test_from.py View on Github external
def check_url(form, field):
    url = form.url.data
    try:
        requests.get(url, timeout=10)
    except Exception as e:
        raise ValidationError(repr(e))


class TestForm(FlaskForm):
    url = StringField('监控网址', validators=[DataRequired("请输入网址!"), check_url])
    selector_type = SelectField('元素选择器类型',
                                choices=[('xpath', 'xpath'),
                                         ('css', 'css selector'),
                                         ('json', 'Jsonpath')])
    selector = StringField('元素选择器', validators=[DataRequired("请输入元素选择器!")])
    is_chrome = SelectField('是否使用无头浏览器',
                            choices=[('no', 'no'), ('yes', 'yes')])
    regular_expression = StringField('正则表达式')
    headers = StringField('自定义请求头')
    submit = SubmitField('提取信息')
github Pagure / pagure / tests / test_pagure_flask_ui_remote_pr.py View on Github external
with tests.user_set(self.app.application, user):

            csrf_token = self.get_csrf()
            data = {
                "csrf_token": csrf_token,
                "title": "Remote PR title",
                "branch_from": "feature",
                "branch_to": "master",
                "git_repo": os.path.join(self.newpath, "test"),
            }
            with patch(
                "pagure.forms.RemoteRequestPullForm.git_repo.args",
                MagicMock(
                    return_value=(
                        "Git Repo address",
                        [wtforms.validators.DataRequired()],
                    )
                ),
            ):

                output = self.app.post(
                    "/test/diff/remote", data=data, follow_redirects=True
                )
                self.assertEqual(output.status_code, 200)

                data["confirm"] = 1
                output = self.app.post(
                    "/test/diff/remote", data=data, follow_redirects=True
                )
                self.assertEqual(output.status_code, 200)
                output_text = output.get_data(as_text=True)
                self.assertIn(
github kasheemlew / learn-python / Exercises / LearnFlask / test1 / app / auth / forms.py View on Github external
def validate_email(self, field):
        if User.query.filter_by(email=field.data).first():
            raise ValidationError('Email already registered.')
github lepture / flask-wtf / tests / base.py View on Github external
return text.decode('utf-8')
    return text


class MyForm(FlaskForm):
    SECRET_KEY = "a poorly kept secret."
    name = StringField("Name", validators=[DataRequired()])
    submit = SubmitField("Submit")


class HiddenFieldsForm(FlaskForm):
    SECRET_KEY = "a poorly kept secret."
    name = HiddenField()
    url = HiddenField()
    method = HiddenField()
    secret = HiddenField()
    submit = SubmitField("Submit")

    def __init__(self, *args, **kwargs):
        super(HiddenFieldsForm, self).__init__(*args, **kwargs)
        self.method.name = '_method'


class SimpleForm(FlaskForm):
    SECRET_KEY = "a poorly kept secret."
    pass


class CaptureHandler(logging.Handler):
    def __init__(self):
        self.records = []
        logging.Handler.__init__(self, logging.DEBUG)
github kvesteri / wtforms-alchemy / tests / test_unique_validator.py View on Github external
def _test_syntax(self, column, expected_dict):
        class MyForm(ModelForm):
            name = TextField()
            email = TextField()

        validator = Unique(
            column,
            get_session=lambda: self.session
        )
        form = MyForm()
        if not hasattr(form, 'Meta'):
            form.Meta = lambda: None
        form.Meta.model = User
        result = validator._syntaxes_as_tuples(form, form.name, column)
        assert result == expected_dict
github orsinium / djburger / tests / validators / pre.py View on Github external
])
    count = wtforms.IntegerField('Count', [
        wtforms.validators.DataRequired(), wtforms.validators.NumberRange(min=0),
    ])


@djburger.validators.wrappers.WTForms
class PreWTFormsWrapped(wtforms.Form):
    name = wtforms.StringField('Name', [
        wtforms.validators.DataRequired(),
    ])
    mail = wtforms.StringField('E-Mail', [
        wtforms.validators.DataRequired(), wtforms.validators.Email(),
    ])
    count = wtforms.IntegerField('Count', [
        wtforms.validators.DataRequired(), wtforms.validators.NumberRange(min=0),
    ])


scheme = dict(
    name=dict(
        type='string',
        required=True,
    ),
    mail=dict(
        type='string',
        required=True,
        # http://docs.python-cerberus.org/en/stable/validation-rules.html#regex
        regex=r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$',
    ),
    count=dict(
        type='integer',