Flask-form使用

base页面就不再写了,参看http://www.pythondoc.com/flask-mega-tutorial/index.html

文件:login.html
{% block body %}
    

Sign In

{# form 对应 login.html中的form #}
{{ form.hidden_tag() }}

{{ form.remember_me }} Remember Me

{% endblock %}

这一点很简单就是 form中有一个提交按钮(),点击之后跳转页面。

@app.route('/login', methods=['GET', 'POST'])
def logintoform():
    myform = LoginForm()
    if myform.validate_on_submit():
        return redirect('/index')
    return render_template('login.html', form=myform)

之所以单写出来是因为我在码代码时发现点击按钮没实现跳转。原因是{{ form.hidden_tag() }}这一句没写,编程方面还是个菜鸟,花费很多时间才找到问题所在。


关于这行代码的解释:

hidden_tag():

Render the form's hidden fields in one call.

A field is considered hidden if it uses the [`HiddenInput`] widget.

If `fields` are given, only render the given fields that are hidden. If a string is passed, render the field with that name if it exists.

Changed in version 0.13: No longer wraps inputs in hidden div. This is valid HTML 5.

Changed in version 0.13: Skip passed fields that aren't hidden. Skip passed names that don't exist.

validate_on_submit():
Call validate() only if the form is submitted. This is a shortcut for form.is_submitted() and form.validate().

没看太懂,又翻看Flask-wtf文档

If your form has multiple hidden fields, you can render them in one block using hidden_tag().

{{ form.hidden_tag() }} {{ form.name.label }} {{ form.name(size=20) }}

Validating Forms

Validating the request in your view handlers:

@app.route('/submit', methods=('GET', 'POST'))
def submit():
    form = MyForm()
    if form.validate_on_submit():
        return redirect('/success')
    return render_template('submit.html', form=form)

你可能感兴趣的:(Flask-form使用)