【发布时间】:2021-06-24 05:30:58
【问题描述】:
我有一个使用 Flask 和 SQLAlchemy 的网上商店,我在主页上实现了分页,路径如下:
@app.route('/')
@app.route('/home')
def home():
page = request.args.get('page', 1, type=int)
data = Product.query.paginate(page=page, per_page=6)
return render_template('home.html', data=data)
我遇到的问题是这样的搜索功能:
@app.route('/search', methods=['GET', 'POST'])
def search():
query = request.args['search']
if len(query) > 0:
page = request.args.get('page', 1, type=int)
data = Product.query.filter(Product.name.ilike(f"%{query}%")).paginate(page=page, per_page=6)
if data is not None:
return render_template('home.html', data=data)
elif data is None:
return redirect(url_for('home'))
if len(query) == 0:
return redirect(url_for('home'))
这是我的search 表单:
<li class="nav-item">
<form class="form-inline" action="{{ url_for('search') }}">
<input class="form-control mr-sm-2 ml-2" name="search" type="search" placeholder="Търсене" aria-label="Search">
<button class="btn btn-outline-info my-2 my-sm-0" type="submit"><i class="fa fa-search"></i></button>
</form>
</li>
这是我的home.html 中的页码jinja2 代码:
{% for page_num in data.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
{% if page_num %}
{% if data.page == page_num %}
<a class="btn btn-info mb-4" href="{{ url_for('home', page=page_num) }}">{{ page_num }}</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{{ url_for('home', page=page_num) }}">{{ page_num }}</a>
{% endif %}
{% endif %}
{% endfor %}
当我搜索产品时,查询会显示正在搜索的项目,但如果有多页结果,当我单击页码时,它会重定向到 home.html,其中包含来自第一条路线的所有数据。
有没有办法让搜索后的结果和search函数的页面保持一致?
【问题讨论】:
-
我认为当您搜索并单击页码时,它会将您带到该页面,但会为您提供所有记录,而不是通过搜索过滤,对吗?并且您想要点击页码时的过滤结果?
-
是的,这正是我想要的。
-
我看到
url_for('home', page=page_num)这是在做什么,因为我在\home的路由中看不到任何命名参数。如果你不介意你能给我像github或discord这样的代码,因为我有同样的问题。还有你的 html 搜索代码是什么 -
看看你为什么要通过
page=page_num,如果你通过了,那么你的路线应该是@app.route("/home<page>") def home(page): [....] -
为什么不尝试将搜索参数
url_for('home', page=page_num, search=searched_string )传递给anchor标记。
标签: python flask sqlalchemy