【问题标题】:How to get the value of html attributes to use it in flask with mysql_db如何获取 html 属性的值以在带有 mysql_db 的烧瓶中使用它
【发布时间】:2021-07-19 22:28:12
【问题描述】:

我正在尝试使用烧瓶和原始 mysql 制作电子商务网站,即使用 flask_mysqldb 编写我自己的 mysql 查询。我正在尝试使用动态路由根据其 ID 在单个模板中显示数据,以避免为不同的产品创建多个模板。但是我被卡住了,因为我无法获取产品的 ID 以将其作为 mysql 查询中的参数传递。如何获取html标签属性值作为参数传递给sql查询??
我的路线:

@app.route('/products/')
def product_details():
    cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    productID = request.args.get('id')
    print(productID)
    
    cursor.execute('SELECT productCode, productName FROM Products WHERE productCode = %s', (productID, )
    )
    products = cursor.fetchone()
    return render_template('product-details.html', products=products)

我的 html 文件

products.html:

<div>
{% for product in products %}
    <h1><a href={{url_for('product_details', pk=product.productCode) }} id={{product.productCode}}>{{product.productName}}</a></h1>
    <p>Rs. {{product.price}}</p>
    {{product.productCode}}
{% endfor %}

产品详细信息.html:

<h1 id={{products.productCode}}>{{products.productName}}</h1>

【问题讨论】:

    标签: python html mysql flask


    【解决方案1】:

    问题是由于您发送到的查询参数与product_details 中的预期参数不匹配造成的。

    您在url_for 呼叫中发送pk,但在productID = request.args.get('id') 中寻找id

    解决办法是在product_details:productID = request.args.get('pk')中寻找pk

    请注意,url_for 调用之外的任何信息对 Flask 不可见,即 Flask 无权访问 &lt;a&gt; 标记的 id 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2023-02-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多