我是 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 %}

最佳答案

您仍然必须使用 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)

关于python - Flask 中的 WTForms : UndefinedError: 'form' is undefined,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34083843/

10-11 19:37