美文网首页
Flask-form使用

Flask-form使用

作者: FirmStone | 来源:发表于2018-07-09 22:40 被阅读0次

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

文件:login.html
{% block body %}
    <h1>Sign In</h1>

    {# form 对应 login.html中的form #}
    <form action="" method="post" name="huForm">
        {{ form.hidden_tag() }}
        <p>{{ form.remember_me }} Remember Me</p>
        <p></p>
    </form>
{% endblock %}

这一点很简单就是 form中有一个提交按钮(<input type="submit" value="Sign In">),点击之后跳转页面。

@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 method="POST" action="/">
    {{ form.hidden_tag() }}
    {{ form.name.label }} {{ form.name(size=20) }}
    <input type="submit" value="Go">
</form>

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使用

      本文链接:https://www.haomeiwen.com/subject/vlrxpftx.html