python - How to update SQLite table based on checkbox value in Flask?
问题描述
I have SQLite database which contains data regarding products such as Product Name
, Description
and Like
which shows if the user likes or doesn't like the product.
A user search for different products which populate a table with the name, description and a checkbox which is clicked in if the value of Like
is 1 in the database and unchecked if not.
I have implemented the button through (as seen in index.html
)
<form method = "POST"> <input type="checkbox" name="like" {% if product.like == 1 %} checked {% else %} {% endif %}>
I now want the user to be able to check and uncheck the boxes in the table, and then press a button that updates the Like
column in the database, how do I do this?
(I can't even access the value of the button in app.py
. When trying print(requests.form['like'])
on the line after name=requests.form['search']
it returns 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
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 %}
解决方案
我想您需要使用 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>
推荐阅读
- javascript - 获取 id 值并将其设置为反应状态
- mongodb - 我们可以在 ubuntu 19.10 上安装 mongo db 吗?
- apache - phpMyAdmin 适用于所有 apache 域
- django - Django 模板 - 使用不同的变量两次使用相同的块
- mysql - 如何在 PostgreSQL 中关闭严格模式
- java - jhipster公司注册内如何创建子用户
- django - 如何在同一 html 中创建包含主模型及其 ForeignKey 的 UpdateView 表单?
- python - 为什么我不能在交互模式下使用 matplotlib 绘制图形?
- batch-file - 如何在我的程序中打开特定的文件扩展名
- java - 检查包含密钥并检查 JSON 中的空/空的最佳实践?