过滤结果和分页
问题描述:
我有一个模板,显示一个过滤器的形式,并在它下面的结果记录列表。我将表单绑定到请求,以便过滤器表单将自身设置为用户在返回结果时提交的选项。过滤结果和分页
我也使用分页。使用分页文档中的代码意味着当用户单击下一页时,表单数据将丢失。
以这种方式处理分页和过滤的最佳方法是什么?
- 将querystring传递给paginiation链接。
- 将分页链接更改为表单按钮,因此同时提交过滤器表单,但是这是假设用户没有弄错过滤器选项。
- 如上所述,但原始数据为隐藏字段。
ALJ
答
如果你不介意的调整您的网址一点你可以嵌入过滤器选项直接进入网址。这实际上具有使搜索选项具有书签功能的好处。因此,当用户单击分页上的下一个/上一个按钮时,所有信息都将从URL中继承。
虽然您可能必须将该网页的网址分开。如果你已经在视图函数中使用了一些关键字参数,你可以将该视图的所有逻辑放在一个函数中。
简单的例子
在你的urls.py
urlpatterns = patterns('',
(r'^some_url/to/form/$', 'myapp.myview'),
(r'^some_url/to/form/(?P<filter>[^/]+)/$', 'myapp.myview'),
)
然后在view.py
def myview(request, filter=None):
if request.method == 'POST':
# if the form is valid then redirect the user to the URL
# with the filter args embedded
elif filter is None:
form = MyForm() # init it with the blank defaults
elif filter is not None:
# Convert your filter args to a dict
data = {'my_form_field' : filter}
form = MyForm(data)
else:
# Sanity checking just in case I missed a case. Raise an exception.
# the rest of the display logic for the initialized form
当然,还有这里使用这样的解决方案不适用的情况,但不知道更多关于你的具体情况,我不能说。
希望这会有所帮助!
实际上,最终我将过滤器硬编码到链接中,这不是很优雅,但工作。 – alj 2011-03-16 12:29:03