【问题标题】:Flask pagination redirect烧瓶分页重定向
【发布时间】: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&lt;page&gt;") def home(page): [....]
  • 为什么不尝试将搜索参数 url_for('home', page=page_num, search=searched_string ) 传递给 anchor 标记。

标签: python flask sqlalchemy


【解决方案1】:

您可以使用 javascript 更新 url 中的查询

此函数将在当前 url 中使用两个参数搜索键,如果存在则更新它,否则添加它。

js

function url_manager(key,value){
const url = new URL(window.location.href);
url.searchParams.set(key,value );
window.location.replace(url)
}

将锚标签替换为按钮标签&lt;button class="page_num_btn_class btn btn-info mb-4" type="button"&gt;{{ page_num }}&lt;/button&gt;

注意-你必须包含 jquery

<script src="https://code.jquery.com/jquery-3.1.0.js" ></script>

你可以在按钮上调用点击事件

$(".page_num_btn_class").click(function (e){
url_manager("page",$(this).text())
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-26
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2014-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多