我有一個網頁,應該允許用戶通過輸入專案名稱來搜索資料庫,或者收集特定類別的所有專案。
我想象這涉及兩個 POST 請求,雖然我有搜索專案名稱的功能,但我無法弄清楚如何在同一個 html 頁面中創建第二個 POST 請求以進行按類別搜索功能。任何幫助將非常感激。

這是我用于搜索的 python 函式。不過,我還沒有為“按類別搜索專案”POST 請求包含任何代碼。
@app.route("/search/", methods = ["GET", "POST"])
def search():
if request.method == "POST":
searchQuery = request.form
query = searchQuery['query']
results = SqlFunctions.searchName(mycursor, query)
return render_template("search.html", results = results)
# pseudo code for what the other POST request might look like
# if request.method == 'POST':
# searchQuery = request.form
# query = searchQuery['query']
# results = SqlFunctions.searchCategory(mycursor, query)
# return render_template("search.html", results = results)
return render_template("search.html", results = None)
這是我用于搜索頁面的 HTML
{% extends "master.html"%}
{% block main %}
<form class="form" action="" method="POST">
<div>
<div class="banner">
<h1>Find Your Expenses Easily</h1>
</div>
<br />
<div class="row">
<div class="column">
<div class="item">
<label for="fname">Search by item name<span>*</span></label>
<input id="fname" type="text" name="query"/>
</div>
<span id="result"></span>
<form>
<button type="submit" id="calc" value="sName">Submit</button>
</form>
</div>
<div class="column">
<div class="item">
<label for="fname">Search by item category<span>*</span></label>
<br />
<select name="query">
<option selected value="" disabled selected></option>
<option value="1" {% if category is defined and category =='Groceries' %} selected="selected" {%endif%}>Groceries</option>
<option value="2" {% if category is defined and category =='Transportation' %} selected="selected" {%endif%}>Transportation</option>
<option value="3" {% if category is defined and category =='Entertainment' %} selected="selected" {%endif%}>Entertainment</option>
<option value="4" {% if category is defined and category =='Rent' %} selected="selected" {%endif%}>Rent</option>
<option value="5" {% if category is defined and category =='Utilities' %} selected="selected" {%endif%}>Utilities</option>
<option value="6" {% if category is defined and category =='Gifts' %} selected="selected" {%endif%}>Gifts</option>
<option value="7" {% if category is defined and category =='Personal' %} selected="selected" {%endif%}>Personal</option>
<option value="8" {% if category is defined and category =='Other' %} selected="selected" {%endif%}>Other</option>
</select>
</div>
<span id="result"></span>
<form>
<button type="submit" id="calc" value="sCategory">Submit</button>
</form>
</div>
</div>
</div>
{% if results is not none %}
<div>
{% include "table.html" %}
{% endif %}
</div>
</form>
{% endblock %}
uj5u.com熱心網友回復:
我通常使用兩種形式而不是這樣做:
if request.method == "POST":
我做這樣的事情(通過我使用 WTForms 的方式):
if form1.validate_on_submit():
# process the first form data
if form2.validate_on_submit():
# process the second form data
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/375547.html
