jinja2.exceptions.UndefinedError:即使在render_template中传递了“ form”之后,“ form”也是未定义的

时间:2019-09-13 06:35:16

标签: python flask flask-wtforms

我已经制作了WTForm,但是无法加载。我在另一个项目中制作了类似的表格,与复制代码并相应地更改了代码的地方不同。但是现在它显示'form'undefined 错误。 发生错误的代码如下:

c = [('COMPANY','COMPANY'),('DISTRIBUTOR','DISTRIBUTOR'),('OUTLET','OUTLET')]

@app.route('/') # Decorator to create url routing, '/' = Home route
def index():
    return render_template('index.html')

# User Registration
class Registration(Form):
    reg_name = StringField('Name',[validators.Length(min=5,max=20), validators.DataRequired()])
    reg_email = StringField('Email',[validators.DataRequired()])
    reg_category = SelectField(label='Category', choices=c)
    reg_password = PasswordField('Password',[validators.Length(min=5,max=15), validators.DataRequired(), validators.EqualTo('reg_confirm', message='Password do not match')])
    reg_confirm = PasswordField('Confirm Password')

@app.route('/register', methods=['GET','POST'])
def register():
    form = Registration(request.form)
    if request.method == 'POST' and form.validate():
        return render_template('index.html')
    return render_template('index.html',form=form)

这是我的 app.py 脚本

<span class="col-md-6 float-right">
        {% from 'includes/_formhelpers.html' import render_field %}
        <form method="POST" action="">
            <div class="form-group">{{render_field(form.reg_name, class_="form-control")}}</div>
            <div class="form-group">{{render_field(form.reg_email, class_="form-control")}}</div>
            <div class="form-group">{{render_field(form.reg_category, class_="form-control")}}</div>
            <div class="form-group">{{render_field(form.reg_password, class_="form-control")}}</div>
            <div class="form-group">{{render_field(form.reg_confirm, class_="form-control")}}</div>
            <button type="submit" class="btn btn-primary">Register</button>
        </form>
    </span>

这是我尝试呈现表单的 index.html

1 个答案:

答案 0 :(得分:1)

index.html由视图函数indexregister呈现。但是您忘记了在视图form中传递index实例。