[英]UnboundLocalError Python-flask
当我尝试从 mysql 数据库中存在的目录表中查询类别时,发生 UnboundLocalError。 UnboundLocalError:分配前引用的局部变量“类别”。 我正在尝试通过数据库表产品添加产品。 我需要 select 类别表中该产品的类别。 我使用 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)
这是我的购物.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>
这是因为这一行:
category = categories.query.all()
仅在发出 POST 请求时执行。 首次加载页面 (GET) 时,变量category
未初始化。
您可以简单地将这一行移到 add_product 例程的顶部,移出if
块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.