Flask-Bootstrap quick_form认为从render_template传入的表单是未定义的

时间:2015-09-25 15:00:01

标签: python flask flask-wtforms jinja2

我正在尝试使用Flask-Bootstrap quick_form呈现WTF表单。但是,我收到form未定义的错误,即使我将其传递给render_template。为什么这不起作用?

File "/home/eron/anaconda/lib/python2.7/site-packages/flask_bootstrap/templates/bootstrap/wtf.html", line 190, in template
    {{ form.hidden_tag() }}

File "/home/eron/anaconda/lib/python2.7/site-packages/jinja2/environment.py", line 397, in getattr
    return getattr(obj, attribute)
UndefinedError: 'form' is undefined
from flask.ext.wtf import Form

class NameForm(Form):
    name = StringField('Login', validators=[Required()])
    submit = SubmitField('Submit')

@app.route('/base', methods=['GET','POST'])
def index():
    name = None
    form = NameForm()

    if form.validate_on_submit():
        name = form.name.data
        session['name'] = form.name.data
        return redirect(url_for('base'))

    return render_template('base.html', form=form)
{% extends "bootstrap/base.html" %}
{% import  "bootstrap/wtf.html" as wtf %}

<div class="col-md-3">
    {{ wtf.quick_form(form) }}
</div>

3 个答案:

答案 0 :(得分:2)

这个答案已经晚了将近2年,但我有一个类似的问题,并且我想分享。 您可以将“表单”更改为“blogform”。似乎Jinja与您从Flask-WTF导入的“Form”模块混淆:

from flask.ext.wtf import Form

您只需将变量名称更改为“form”以外的其他名称,例如“blogform”:

@app.route('/base', methods=['GET','POST'])
def index():
    name = None
    blogform = NameForm()

    if blogform.validate_on_submit():
        name = blogform.name.data
        session['name'] = blogform.name.data
        return redirect(url_for('base'))

    return render_template('base.html', blogform=blogform)

由于render_template中传递的变量现在已更改为blogform,因此在HTML文件中也会相应地更改它:

{% extends "bootstrap/base.html" %}
{% import  "bootstrap/wtf.html" as wtf %}

<div class="col-md-3">
    {{ wtf.quick_form(blogform) }}
</div>

答案 1 :(得分:0)

你写道:
class NameForm(Form):
然后
return render_template('base.html', form=form)

首先尝试将form = form更改为Form = Form

如果这不起作用,请尝试删除form = NameForm()并重试。

答案 2 :(得分:-2)

删除     来自div标签的{%import“bootstrap / wtf.html”as wtf%}并将其放在其末尾