Flask - WTF - Input Required Validator - 限制发布请求(留在页面上)

Flask - WTF - Input Required Validator - Restrict the request from being posted (Stay on page)

我正在学习如何在新的应用程序概念验证中结合使用 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

我遇到的问题是,我不想实际渲染模板(它就在那里,因为我现在必须 return 做出回应)。并且屏幕上没有闪烁错误。

如何限制导航直到框中有 x 个字符?并在未通过验证时闪烁消息?

感谢阅读

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

The Form will validate_on_submit() properly

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

The Issue I have is, I do not want to actually render the template (It's just there cuz I have to return a response for now). And no error is flashed on screen.

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

How do I restrict the navigation until x characters are in the box? and flash the message if it does not validate?

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

调用模板中的字段时传递max_length=3即可实现:

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

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