Flask中的WTForms:UndefinedError:' form'未定义

时间:2015-12-04 08:26:18

标签: python flask wtforms

我是Flask和WTForms的新手,我无法渲染我的HTML页面。我一次又一次地浏览了WTforms文档,但我无法找到错误的来源:

jinja2.exceptions.UndefinedError, UndefinedError: 'form' is undefined

我的代码如下:

forms.py

from flask.ext.wtf import Form
from wtforms import TextField, BooleanField, TextAreaField, StringField, PasswordField, SelectField, validators

class LoginForm(Form):
    username = TextField('Username', [
        validators.Required(), 
        validators.Length(min=4, max=25)
    ])
    password = PasswordField('New Password', [
        validators.Required()
    ])

app.py

from forms import *
from wtforms import Form, fields, BooleanField, TextField, StringField,     PasswordField, validators
from werkzeug.security import generate_password_hash, \
 check_password_hash

@app.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        if load_user(form.username.data) is None:
            flash('Invalid username')
        else: 
            if check_password_hash(cred.password, form.password.data):
                return redirect(url_for('browse'))  
            else: 
                flash('Invalid password')
    return render_template('login.html', title='Login', form=form)

的login.html

{% extends "base.html" %}
{% block body %}
    <form action="{{ url_for('login') }}" method="Post">
        <fieldset>
            <div>{{ form.username.label }}: {{ form.username() }}</div>
            <div>{{ form.password.label }}: {{ form.password() }}</div>
            <div class="form-group">
                <button class="btn btn-default" type="submit">
                    <span aria-hidden="true" class="glyphicon glyphicon-log-in"></span>
                    Log In
                </button>
            </div>
        </fieldset>
    </form>    
    <div>
    or <a href="new">Register</a> for an account
    </div>
{% endblock %}

1 个答案:

答案 0 :(得分:6)

您还必须使用return声明 - 例如:

return render_template('login.html', title='Login', form=form)

在所有if-else分支中,否则form上下文变量不会传递给模板。 login函数应如下所示:

@app.route('/login/', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        if load_user(form.username.data) is None:
            flash('Invalid username')
            return render_template('login.html', title='Login', form=form)
    else: 
        if check_password_hash(cred.password, form.password.data):
            return redirect(url_for('browse'))  
        else: 
            flash('Invalid password')
            return render_template('login.html', title='Login', form=form)
    return render_template('login.html', title='Login', form=form)