-1

当我尝试从 mysql 数据库中存在的目录表中查询类别时,发生 UnboundLocalError。UnboundLocalError:分配前引用的局部变量“类别”。我正在尝试通过数据库表产品添加产品。我需要从类别表中选择该产品的类别。我使用 query.all() 来做到这一点。这是apps.py

@app.route('/AddProduct',methods=["GET", "POST"])
def add_product():
    if request.method =="POST":
        name=request.form['name']
        price=request.form['price']
        description = request.form['description']
        category = categories.query.all()
        image = request.files['image']
        if image and allowed_file(image.filename):
            filename = secure_filename(image.filename)
            image.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        #cursor = mysql.connection.cursor()
        #cursor.execute('SELECT * FROM categories')
        #account = cursor.fetchall()
        cursor.execute('INSERT INTO products VALUES(NULL,% s,% s,% s,% s,% s)',(name,price,description,image,categoryId))
        mysql.connection.commit()
    return render_template('Shopping.html',category=category)

这是我的 shopping.html 文件

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Admin</title>
  </head>
  <body>
      <form action="/home" method="POST" enctype="multipart/form-data" class="register-form" id="register-form">
        <input type="text" name="name" id="name" placeholder="Product Name"/>
        <input type="" name="price" id="price" placeholder="price"/>
        <input type="text" name="description" id="description" placeholder="description"/>
         <input type="file" name="image"><br>
         <label for="category">ADD catogory</label>
         <select name="category" id="category" class="form-control" required>
           <option value="">Select a category</option>
           {% for cat in category %}
           <option value="cat.categoryId">{{cat.categoryName}}</option>
           {% endfor %}

         <input type="submit">
      </form>
4

1 回答 1

0

这是因为这一行:

category = categories.query.all()

仅在发出 POST 请求时执行。首次加载页面 (GET) 时,变量category未初始化。

您可以简单地将这一行移到 add_product 例程的顶部,移出if块。

于 2021-05-02T19:57:07.937 回答