Flask-WTF形式无法获取数据

时间:2014-09-24 04:44:19

标签: python flask wtforms flask-wtforms

我使用Flask-WTF提交表单,但我遇到了一些困难,我似乎无法找到任何帮助或其他示例。我的代码如下,但这是我迄今为止所发现的内容。 form.validate_on_submit()未评估为true,因此它正在跳过整个块。接下来,我试着看看python读取的请求发生了什么。当我打印出" form.username.data"的值(在我初始化LoginForm之后);它打印出来"无"所以似乎表格没有正确创建?

我检查了浏览器发送的帖子请求,并且该请求中的所有信息都可见!

这是我的登录表单代码:

   from flask.ext.wtf import Form
      from wtforms import TextField, PasswordField
      from wtforms.validators import Required

     class LoginForm(Form):
      username = TextField('username', validators = [Required()])
      pin = PasswordField('pin', validators = [Required()])

这是路线逻辑:

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

    if g.user is not None and g.user.is_authenticated():
        return redirect(url_for('index'))


    form = LoginForm(request.form)

    print form.errors

    if form.validate_on_submit():
        if form.username is None or form.username == "":
            print "invalid user"
            flash('Invalid login. Please try again.')
            return redirect(url_for('login'))
        user = db.session.query(User).filter_by(username=form.username).filter_by(password=form.pin).first()
        print user
        if user is None:
            flash('User does not exist. Please register.')
            return redirect(url_for('welcome'))

        login_user(user)
        return redirect(url_for('dashboard'))
    print "didn't validate"
    return render_template('login.html', title = 'Sign In', form = form)

配置代码:

CSRF_ENABLED = True

以下是HTML格式:

{% extends 'base.html' %}

{% block content %}
<h1>Sign In</h1>
<form action="" method="post" name="login">
    {{ form.hidden_tag()}}
    <p>
        Please enter your username:<br>
        {{ form.username }}<br>
    </p>
    <p>
        Please enter your pin:<br>
        {{ form.pin }}<br>
    </p>
    <p><input type="submit" value="Sign In"></p>
</form>
{% endblock %}

我已经好好看了几天,但我不知道接下来要做什么。我有什么指针或任何明显的缺失吗?

3 个答案:

答案 0 :(得分:2)

form = LoginForm()

并可以按如下方式优化代码:

form = LoginForm() if request.method == 'POST' else LoginForm(request.args)
if form.validate_on_submit():
    if login_user(form.user, remember=form.remember_me.data) is True:
        flash(_('Logged in successfully.'))
    return redirect(form.next.data or url_for('index'))
return render_template('users/login.html', form=form)

答案 1 :(得分:1)

请勿使用LoginForm初始化request.form课程。

form = LoginForm()

答案 2 :(得分:0)

如果你正在使用flask-WTF,请确保将csrf_token放在表单中:

<form method="POST" action="<page for action>">
    {{ name-of-form.csrf_token }}
    ....
    {{ wtf.form_field(name-of-form.name-of-submit-button) }}
</form>