目前我有一个瓶子应用程序,它从一个 sqlite 数据库中读取元素并将它们显示在一个表格中(使用啤酒,因为......我喜欢啤酒)。我希望能够使用表格行中的加减按钮调整表格中的数字(金额)。这两个按钮都应该更新数据库中的金额,并刷新页面上显示的金额。
这是 python /瓶子部分:
@app.route('/')
@app.route('/display')
def display():
conn = sqlite3.connect('beers.db')
c = conn.cursor()
c.execute("SELECT id, brewer, beer, amount FROM beer;")
result = c.fetchall()
c.close()
output = template('make_table', rows=result)
return output
这是当前模板,带有加减按钮。
<p>The available beers are:</p>
<table border="1">
%for row in rows:
<tr>
%for col in row:
<td>{{col}}</td>
%end
<td><input type ="button" value="Add"></td>
<td><input type ="button" value="Subtract"></td>
</tr>
%end
</table>
谢谢你的帮助!
最佳答案
使用 /display
方法添加 POST
路由。
在此,获取 beer ID 的值,以及用户是否单击 Add 或 Sub。
完成此操作后,您将获得啤酒 ID 和要执行的操作,您只需使用 DB 执行操作,然后重定向到 /display
页面。
这是 Bottle 应用程序代码:
@app.route('/display', method='POST')
def display_mod():
#You get the value of each button : None if non clicked / Add or Sub if clicked
add = request.POST.get('Add')
sub = request.POST.get('Sub')
# b_id is the ID of the beer the user's clicked on (either on add or sub)
b_id = request.POST.get('beer_id')
if add is not None:
# do something
redirect("/display")
if sub is not None:
# so something
redirect("/display")
然后,更改您的模板以包含表单并更改提交按钮中的两个按钮。您还需要放置一个
hidden
输入,以便您可以将数据传递给应用程序。<p>The available beers are:</p>
<table border="1">
%for row in rows:
<tr>
<!-- Here you grab the beer's ID that you'll use later -->
%p_id = row[0]
%for col in row:
<td>{{col}}</td>
%end
<form action="/display" method="POST">
<!-- input type hidden, and value is the ID of the beer -->
<input type = "hidden" name ="beer_id" value= "{{p_id}}">
<td><input type ="submit" name="Add" value="Add"></td>
<td><input type ="submit" name="Sub" value="Subtract"></td>
</form>
</tr>
%end
</table>
给你。希望它有帮助(如果是这样,不要害羞,送我一瓶啤酒!)
关于python - 在瓶子生成的网页上添加和减去按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30513805/