jinja2.exceptions.UndefinedError:'form'未定义

时间:2019-08-25 08:44:48

标签: python flask jinja2 flask-wtforms

我正在尝试在引导程序模式下添加表单,并且该表单是使用WTForms创建的,但无法在render_template中获取上下文变量。 我已经点击了此链接(Flask Mega Tutorial - jinja2.exceptions.UndefinedError: 'form' is undefined),但问题尚未解决。

# Warehouse
class Warehouse_Add(Form):
    product_name = StringField('Product Name',[validators.Length(min=5,max=10), validators.DataRequired()])
    product_price = StringField('Price',[validators.DataRequired()])
    product_qty = StringField('Quantity',[validators.DataRequired()])

@app.route('/warehouse', methods=['GET','POST'])
def warehouse_add():
    form = Warehouse(request.form)
    if request.method == 'POST' and form.validate():
        product_name = form.product_name.data
        product_price = form.product_price.data
        product_qty = form.product_qty.data
        cur = mysql.get_db().cursor()
        cur.execute('INSERT INTO company_warehouse(name, price, qty) VALUES(%s, %s, %s)',(product_name,product_price,product_qty))
        mysql.get_db().commit()
        cur.close()
        flash("Product Added!!","success")
        redirect(url_for('dashboard'))
    return render_template('dashboard.html',form=form)

这是 Python 代码

{% from "includes/_formhelpers.html" import render_field %}
      <form action="" method="POST">
      <div class="modal-body">
        <div class="form-group row">
          <div class="form-group row">{{render_field(form.product_name,class_="form-control")}}</div>
        </div>
        <div class="form-group row">
          <div class="form-group row">{{render_field(form.product_price,class_="form-control")}}</div>
        </div>
        <div class="form-group row">
          <div class="form-group row">{{render_field(form.product_qty,class_="form-control")}}</div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="reset" class="btn btn-danger">Reset</button>
        <button type="submit" class="btn btn-success">Submit</button>
      </div>
    </form>

这是模板部分

1 个答案:

答案 0 :(得分:0)

您能否提供此“表格未定义的错误”出现的位置。那么发生错误时哪一行代码,甚至更好的是整个堆栈跟踪?

编辑:

https://stackoverflow.com/a/19506148/11333207中所指。尝试使用这种形式。

@app.route('/warehouse', methods=['GET','POST'])
def warehouse_add():

    form = Warehouse()

    if form.validate_on_submit():

        product_name = form.product_name.data
        product_price = form.product_price.data
        product_qty = form.product_qty.data
        cur = mysql.get_db().cursor()
        cur.execute('INSERT INTO company_warehouse(name, price, qty) VALUES(%s, %s, %s)',(product_name,product_price,product_qty))
        mysql.get_db().commit()
        cur.close()
        flash("Product Added!!","success")
        redirect(url_for('dashboard'))
    return render_template('dashboard.html',form=form)