如何在使用webhelpers.paginate分页时保留查询参数
我在为我的Turbogears 2项目寻找一个分页的例子,找到了这个网站:http://rapidprototype.ch/bg2docs/tg2pagination.html,效果很好。不过,我在更换页面时遇到了一个关于查询参数的问题。
这是我在控制器中列出内容时的代码。
def list(self, page=1, **kw):
q = ""
if kw.has_key('q'):
log.debug("searching %s" % kw)
q = kw['q']
if kw.has_key('all'):
q = ""
products = DBSession.query(model.Product).filter(
or_(model.Product.name.like('%%%s%%' % q),
model.Product.description.like('%%%s%%' % q),
model.Product.model.like('%%%s%%' % q),
model.Product.code.like('%%%s%%' % q))).all()
def get_link(product):
return Markup("""<a href="form?id=%s">%s</a>""" % (product.id, product.id))
product_fields = [
(Markup("""<a href="?s=id">Id</a>"""), get_link),
(u'Name', 'name'),
(u'Model', 'model'),
(u'Code', 'code'),
(u'Description', 'description')]
product_grid = MyDataGrid(fields = product_fields)
currentPage = paginate.Page(products, page, items_per_page=50)
return dict(currentPage=currentPage,
title=u'Products List', item=u'product', items=u'products',
data=currentPage.items,
grid=product_grid,
page=u'Search %s results' % q,
q=q,
hits=len(products))
这是html模板的一部分。
<h1>List of ${items}</h1>
<form action="list" method="get">
<input name="q" type="text" value="${value_of('q', default='')}"/>
<input type="submit" value="Search"/> <input type="submit" name="all" value="All"/>
</form>
${hits} ${items} found
<p class="pagelist">${currentPage.pager(format='$link_first ~3~ $link_last')}</p>
<div>
${grid(data)}
</div>
<p><a href="${tg.url('form')}">Add a ${item}</a></p>
搜索功能正常,生成的链接像这样:'/list?q=cable',但是当我点击分页的页面“1,2...8,9”时,链接变成了'/list?page=2'。
我该如何将之前的查询参数或其他参数添加到这个链接中呢?
3 个回答
0
你可以像下面的代码片段那样更新请求参数。
def paginate(self, items, items_per_page=20):
"""https://bitbucket.org/bbangert/webhelpers/src/acfb17881c1c/webhelpers/paginate.py"""
current_page = self.request.GET.get('page') or 1
def page_url(page):
params = self.request.params.copy()
params['page'] = page
return self.request.current_route_url(_query=params)
return Page(collection=items, page=current_page, items_per_page=items_per_page, url=page_url)
1
你应该使用这样的语法:
currentPage.kwargs['q'] = q
currentPage = paginate.Page(
products,
page,
items_per_page=50,
q = q
)
1
在命令行上试了一段时间后,我觉得我找到了一个解决办法。
在currentPage里定义了一个kwargs字典(这个字典是从paginate.Page赋值过来的),所以我做了一些实验,发送参数,结果成功了。这就是我的做法。
currentPage = paginate.Page(products, page, items_per_page=50)
currentPage.kwargs['q'] = q
return dict(currentPage=currentPage,
title=u'Products List', item=u'product', items=u'products',
data=currentPage.items,
grid=product_grid,
page=u'Search %s results' % q,
q=q,
hits=len(products))
现在我得到了这样的链接:'/list?q=cable&page=2' 还在想这是不是最好的解决方案或者说是最佳实践。