1
我想從用戶輸入到搜索框中的「名稱」和「大小」值中獲取值。燒瓶 - 獲取值
但顯而易見的問題是,我試圖得到值從method: "POST"
hmtl形式。 而我的html操作只是引用{{ url_for('main') }}
html,而不是要在{{url_for('search')}} html中檢索這些值的位置。
這裏是模板:
import sqlite3
from flask import Flask,render_template, url_for, redirect, request
app = Flask(__name__)
conn = sqlite3.connect('shoes.db', check_same_thread=False)
c = conn.cursor()
@app.route("/", methods=["GET", "POST"])
def main():
if request.method == 'GET':
return render_template('main.html')
elif request.method == 'POST':
name = request.form.get('name')
size = request.form.get('size')
return redirect(url_for('search'))
@app.route("/search/", methods=["GET", "POST"])
def search():
# Need to get the 'name' and 'search' values from input, so this way is incorrect.
name = request.args.get("name")
size = request.args.get("size")
c.execute("SELECT * FROM shoes WHERE name LIKE ? AND sizes LIKE ? ORDER BY price",
('%'+name+'%','%'+size+'%'))
p = c.fetchall()
url = [p[i][0] for i in range(len(p))]
names = [p[i][1] for i in range(len(p))]
prices = [p[i][2] for i in range(len(p))]
sizes = [p[i][3] for i in range(len(p))]
shoe_type = [p[i][4] for i in range(len(p))]
return render_template('search.html' , url=url, names=names, prices=prices,
sizes=sizes, shoe_type=shoe_type)
if __name__ == '__main__':
app.run(debug=True)
main.html中:
{% extends "layout.html" %}
{% block content %}
<form action = "{{ url_for('main') }}" class="form" method = "POST" >
<h1>Soccer Shoes Finder</h1>
<div class="line-separator"></div>
<div class="container-fluid">
<input name = "name" type="text" placeholder="Name"/>
<input name = "size" type="text" placeholder="Size"/>
<button class="glyphicon glyphicon-search" aria-hidden="true"></button>
</div>
</form>
{% endblock %}
search.html:
{% extends "layout.html" %}
{% block content %}
<div class= "container">
<h2>Results:</h2>
<table class="table table-striped">
<thead>
<tr>
<th>url</th>
<th>Name</th>
<th>Prices</th>
<th>Sizes</th>
<th>Shoe Type</th>
</tr>
</thead>
<tbody>
{% for i in range(url|length) %}
<tr>
<td><a href={{url[i]}}>aa</td>
<td>{{names[i]}}</td>
<td>${{prices[i]}}</td>
<td>{{sizes[i]}}</td>
<td>{{shoe_type[i]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
任何人都知道我怎麼能做到這一點?希望我說的是有道理的。謝謝。
感謝。這工作。可能是一個愚蠢的問題,但如果我刪除了我的main.html中的'重定向',它怎麼知道點擊搜索按鈕時重定向? – tadm123
形式'action'屬性告訴** main.html **頁面直接提交表單到你的**/search/**函數 – abigperson
我看,很有道理。 – tadm123