我试图根据用户先前所做的选择来限制下拉列表中的选择。这是我的 flask 的样子:
初始化.py
@app.route('/create/', methods=['GET','POST'])
def create():
mySQL2 = SelectCustomer(session['ID']) #displayed invoicereceiver
global sessioncur
try:
form = CreateinvoiceForm(request.form)
if request.method == 'POST' and form.validate():
#HEADER
#This fetches from HTML
customer = request.form.get('customer')
goodsrec = request.form.get('goodsrec')
return render_template("createinvoice.html", form=form, mySQL2 = mySQL2)
customer 使用 mySQL2 作为可能的变量从 html 表单中填充以供选择:
html 选择表单
<select required name="customer" class="selectpicker form-control" ,
placeholder="Select">
<option selected="selected"></option>
{% for o in mySQL2 %}
<option value="{{ o[2] }}">{{ o[2] }}</option>
{% endfor %}
</select>
goodsrec 的选择必须取决于选择了哪个客户。 我的想法是按如下方式获取客户 ID:
c, conn = connection()
customerID = c.execute("SELECT Cm_Id FROM customer WHERE Cm_name ='" +
str(customer) +"' limit 1")
customerID = c.fetchone()[0]
然后我可以在一个函数中使用这个值,我必须获得具有该 ID 的 goodsreceivers:
def SelectGoodsrecSEE(customerID):
c,conn = connection()
c.execute("SELECT * FROM goodsrec WHERE Gr_Cm_id=" +str(id))
mySQL8 = c.fetchall()
c.close()
conn.close()
gc.collect()
return mySQL8
到目前为止,我非常确定这会奏效。我不知道的是如何构造 flask 以使其加载第一个选择并考虑到第二个选择。与 html 类似,我必须循环遍历 mySQL8。但是这个结构在 flask 中看起来如何完成呢? 目前我所拥有的看起来像
@app.route('/create/', methods=['GET','POST'])
def create():
mySQL2 = SelectCustomer(session['ID']) #displayed invoicereceiver
global sessioncur
try:
form = CreateinvoiceForm(request.form)
if request.method == 'POST' and form.validate():
#HEADER
#This fetches from HTML
customer = request.form.get('customer')
c, conn = connection()
customerID = c.execute("SELECT Cm_Id FROM customer WHERE Cm_name ='" +
str(customer) +"' limit 1")
customerID = c.fetchone()[0]
mySQL8 = SelectGoodsrecSEE(customerID)
goodsrec = request.form.get('goodsrec')
return render_template("create.html", form=form, mySQL2 = mySQL2)
我需要能够将 mySQL8 传递给 create.html,以便我可以在 html 中从中进行选择。有任何想法吗?希望它或多或少清楚我在找什么..
编辑
SELECT * FROM goodrec WHERE Gr_Cm_id=18;
mySQL8
最佳答案
SQL 注入(inject)风险
首先,您应该改进您的 SQL 代码,因为您现在拥有它,很容易受到 SQL 注入(inject)攻击。因此,而不是:
c.execute("SELECT Cm_Id FROM customer WHERE Cm_name ='" + str(customer) + "' limit 1")
推荐的用法是:
sql = 'SELECT Cm_Id FROM customer WHERE Cm_name = %s LIMIT 1'
parameters = [str(customer)]
c.execute(sql, parameters)
一些额外的 SO 帖子讨论了这个问题:
- Python best practice and securest to connect to MySQL and execute queries
- Python MySQL Parameterized Queries
实现级联选择
python :
@app.route('/create/', methods=['GET','POST'])
def create():
mySQL2 = SelectCustomer(session['ID'])
global sessioncur
try:
form = CreateinvoiceForm(request.form)
if request.method == 'POST' and form.validate():
customer = request.form.get('customer')
goodsrec = request.form.get('goodsrec')
# do stuff with submitted form...
return render_template("createinvoice.html", form=form, mySQL2 = mySQL2)
@app.route('/get_goods_receivers/')
def get_goods_receivers():
customer = request.args.get('customer')
print(customer)
if customer:
c = connection()
customerID = c.execute("SELECT Cm_Id FROM customer WHERE Cm_name = %s LIMIT 1", [customer])
customerID = c.fetchone()[0]
print customerID
c.execute("SELECT * FROM goodsrec WHERE Gr_Cm_id = %s", [customerID])
mySQL8 = c.fetchall()
c.close()
# x[0] here is Gr_id (for application use)
# x[3] here is the Gr_name field (for user display)
data = [{"id": x[0], "name": x[3]} for x in mySQL8]
print(data)
return jsonify(data)
HTML/Javascript:
<select name="customer" id="select_customer" class="selectpicker form-control">
<option selected="selected"></option>
{% for o in mySQL2 %}
<option value="{{ o[2] }}">{{ o[2] }}</option>
{% endfor %}
</select>
<select name="goodsrec" id="select_goodsrec" class="selectpicker form-control" disabled>
<option>Select a Customer...</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script charset="utf-8" type="text/javascript">
$(function() {
var dropdown = {
customer: $('#select_customer'),
goodsrec: $('#select_goodsrec')
};
// function to call XHR and update goodsrec dropdown
function updateGoodsrec() {
var customer = dropdown.customer.val();
dropdown.goodsrec.attr('disabled', 'disabled');
console.log(customer);
if (customer.length) {
dropdown.goodsrec.empty();
$.getJSON("{{ url_for('get_goods_receivers') }}", {customer: customer}, function(data) {
console.log(data);
data.forEach(function(item) {
dropdown.goodsrec.append(
$('<option>', {
value: item.id,
text: item.name
})
);
});
dropdown.goodsrec.removeAttr('disabled');
});
}
}
// event listener to customer dropdown change
dropdown.customer.on('change', function() {
updateGoodsrec();
});
});
</script>
关于javascript - Flask:基于先前选择的下拉值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42886965/