【问题标题】:How to update SQLite table based on checkbox value in Flask?如何根据 Flask 中的复选框值更新 SQLite 表?
【发布时间】:2020-02-14 08:01:01
【问题描述】:

我有 SQLite 数据库,其中包含有关产品的数据,例如 Product NameDescriptionLike,它显示了用户是否喜欢该产品。

用户搜索使用名称、描述和复选框填充表格的不同产品,如果Like 的值在数据库中为 1,则单击该复选框,否则未选中。 我已经通过实现了按钮(如index.html 所示)

<form method = "POST"> <input type="checkbox" name="like" {% if product.like == 1 %} checked {% else %} {% endif %}>

我现在希望用户能够选中和取消选中表格中的复选框,然后按下更新数据库中Like 列的按钮,我该怎么做?

(我什至无法访问app.py 中按钮的值。当在name=requests.form['search'] 之后尝试print(requests.form['like']) 时,它返回BadRequestKeyError: The browser sent a request that this server could not understand. KeyError: 'like'

app.py

... 
product = []
@app.route('/', methods = ['POST'])
def index():
   name = None
   if request.method == 'POST':
     name = request.form['search']
     if name is not None or name != "":
        query_product = Products.query.filter(Products.productname==name).first()
        if (query_product is not None) and (query_product not in product):
            company.append(query_company)
   print(company, file = sys.stderr)
   return render_template('index.html', companies = company)

Products

class Products(db.Model):
   index = db.Column(db.Integer(), primary_key = True)
   productname = db.Column(db.String(), primary_key = False)
   description = db.Column(db.String(), primary_key = False)
   like = db.Column(db.Integer(), primary_key = False)
   ...more columns

index.html

 <!-- /templates/index.html  -->

{% extends 'base.html' %}
{% block content %}
    <form method="POST">
        <input type="text" placeholder="Search for Product.." name="search">
        <button type="submit" name="submit">Search</button> <button type="submit" name="update" value = company.index style = margin-left:45%>Update</button>
    <div class="product-container" style="overflow: auto; max-height: 80vh">
        <div class="table-responsive">
            <table class="table" id="products">
                <thead>
                    <tr>
                        <th scope="col">Product Name</th>
                        <th scope="col">Description</th>
                        <th scope="col">Like</th>
                    </tr>
                </thead>
                <tbody>
                {% for product in products %}
                    <tr {{company.index}}>
                        <th scope="row">{{ product.productname}}</th>
                        <td> {{ product.description }} </td>
                        <td><form method = "POST"> <input type="checkbox" name="like" {% if product.like == 1 %} checked {% else %} {% endif %}></form></td>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
{% endblock %}

【问题讨论】:

    标签: python sqlite flask flask-sqlalchemy flask-wtforms


    【解决方案1】:

    我猜您需要使用 javascript 来执行此操作,并向您的后端添加另一条路由,然后更新数据库。

    可能是这样的,如果它应该自动发生:

    <input type="checkbox" onchange="updateLike('productId', this.checked)">
    <script>
    async function updateLike(productId, doesLike) {
        let response = await fetch("http://localhost/products/productId/like", {
            method:"POST",
            headers: {"Content-Type":"application/json"},
            body: JSON.stringify({
                productId: productId,
                like: doesLike
            })
        });
    }
    </script>
    

    或者您可以添加一个将请求发送到服务器的按钮。

    <input type="checkbox" name="like"/>
    <button onclick="updateLike('productId', document.querySelector('input[name=like]').checked)">confirm</button>
    

    【讨论】:

    • 嗨,谢谢,我会试试这个。如何指定应该更新的是我的 SQLite 数据库?哪个是 SQLAlchemy() 数据库对象?
    • 我从未听说过 SQLAlchemy,对不起。但也许这有帮助:stackoverflow.com/questions/9667138/…
    猜你喜欢
    • 2018-07-27
    • 2014-04-26
    • 2020-03-22
    • 1970-01-01
    • 2021-01-21
    • 2015-12-27
    • 2015-03-21
    • 2018-09-03
    • 1970-01-01
    相关资源
    最近更新 更多