Flask - WTF - 输入必需验证器 - 限制发布请求(保留在页面上)

时间:2016-03-15 13:25:05

标签: python flask wtforms flask-wtforms

我正在学习如何将WTForms和Flask一起用于新的应用概念验证。

我有一张表格。目标是要求至少3个姓氏的姓氏。

class PersonByNameForm(Form):
    first_name = StringField('First Name', filters=none_filter)
    last_name = StringField(validators=[InputRequired('Enter a Last Name'), Length(min=3)])
    submit = SubmitField('SUBMIT')

我这样渲染表格

@app.route('/', methods=['GET'])
def index():
    if request.method == 'GET':
        form = PersonByNameForm()
        return render_template('front_page.html', form=form)

HTML

 <form action="person_profiles" method="post">
                {{form.hidden_tag()}}
                {{form.first_name.label}}
                {{form.first_name}}
                {{form.last_name.label}}
                {{form.last_name}}
                {{form.submit}}
            </form>

表单本身将数据发布到

@app.route('/person_profiles', methods=['GET', 'POST'])
def person_profiles():

    if request.method == 'GET':
        # This is just place holder but this view will have copy of the form
        form = PersonByNameForm()
        form2 = FindPersonForm()
        return render_template('person_profile.html', context=[], form=form, form2=form2)

    else:

        form = PersonProfileForm(request.form)

        if form.validate_on_submit():
            query = Session.query(schema.Person)
            first_name = form.first_name.data
            last_name = form.last_name.data
            print(first_name, last_name)
            if first_name:
                query = query.filter(schema.Person.first_name.contains(first_name))
            if last_name:
                query = query.filter(schema.Person.last_name.contains(last_name))

            return render_template('person_profile.html', context=query.all())
        else:
            print(form.errors)
            error = form.errors
            flash_errors(form, 'test')
            return render_template('person_profile.html', error=error, form=form)

表单将validate_on_submit()正确,并进入else块打印{'last_name': ['Enter a Last Name']}

的form.error

我遇到的问题是,我不想实际渲染模板(它只是因为我现在必须返回一个响应)。并且屏幕上没有错误。

如果x字符在框中,我如何限制导航?如果没有验证,请刷新消息?

感谢您阅读

1 个答案:

答案 0 :(得分:0)

我有点不清楚你的问题是什么。

  

表格将正确验证_on_submit()

所以输入的字符串至少有3个字符,对吧?

  

我遇到的问题是,我不想实际渲染模板(它只是因为我现在必须返回一个响应)。并且屏幕上没有错误。

要在调用flash后闪烁错误消息,请使用已输入的值再次渲染模板。您必须渲染一些内容以包含Flash消息。

  

如果x字符在框中,我如何限制导航?如果没有验证,请刷新消息?

在名称中至少包含3个字符之前,是否要阻止提交表单(客户端)?

这可以通过在调用模板中的字段时传递max_length=3来实现:

{{form.last_name(max_length=3)}}

显然,这里的问题是你直接在模板中传递3。 AFAIK,WTForms不会自动为您执行此操作。

相关问题