我已经通读了这个问题的相关帖子,但没有找到一个合适或似乎匹配的答案(如果我错过了,请道歉,我已经看了大约10篇帖子)。
编写搜索页面,查找数据库中的条目。最初,我将其作为两个单独的函数编写。一个显示搜索框,另一个执行实际搜索并返回结果。这很好,但我正试图使它更“用户友好”,方法是将搜索框保持在页面顶部,如果有搜索结果,只返回结果。
这似乎是一件简单的事情,但并不奏效。
views.app中的Python代码
@app.route('/search', methods=['POST'])
def SearchForm():
if request.method == "POST":
output = []
searchterm = request.form['lookingfor']
whichName = request.form['name']
if searchterm:
conn = openDB()
results = findClient(conn, searchterm, whichName)
for r in results:
output.append({'id': r[0], 'fname': r[1], 'lname': r[2], 'phonen': r[3], 'email': r[4], 'started': r[5],
'opt': r[6], 'signup': r[7], 'enddate': findEndDate(r[7], r[5])})
closeDB(conn)
if output:
message = "Record(s) Found"
else:
message = "Nothing found, sorry."
return render_template('search.html', message=message, output=output)
else:
output = []
message = "Please enter a name in the search box"
return render_template('search.html', message=message, output=output)
else:
return render_template('search.html')
用于搜索的HTML.HTML
{% extends "baseadmin.html" %}
{% block content %}
<div>
<form action="{{url_for('search')}}" method="post">
<p>Search for a Client: <input type="text" name="lookingfor"/></p>
<input type="radio" name="name" value="fname" id="fname"><label for="fname">First Name</label>
<input type="radio" name="name" value="lname" id="lname"><label for="lname">Last Name</label>
<input type="submit" value="submit"/>
</form>
</div>
<h2>{{ message }}</h2>
<div>
<table>
<tr>
<th>Name</th>
<th>Email Address</th>
<th>Phone Number</th>
<th>Trial Method</th>
<th>Start Date</th>
<th>EndDate</th>
</tr>
{% for client in output %}
<tr>
<td>{{ client['fname'] }} {{ client['lname'] }}</td>
<td>{{ client['email'] }}</td>
<td>{{ client['phonen'] }}</td>
<td>{{ client['started'] }}</td>
<td>{{ client['signup'] }}</td>
<td>{{ client['enddate'] }}</td>
</tr>
{% endfor %}
</table>
</div>
{% endblock %}