gpt4 book ai didi

python - Flask : UndefinedError: 'form' is undefined 中的 WTForms

转载 作者:太空宇宙 更新时间:2023-11-04 08:04:24 25 4
gpt4 key购买 nike

我是 Flask 和 WTForms 的新手,我无法呈现我的 HTML 页面。翻了一遍WTforms的文档,还是找不到错误的来源:

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

我的代码如下:

表单.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 : UndefinedError: 'form' is undefined 中的 WTForms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34083843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com