过滤结果和分页

时间:2010-04-27 20:51:24

标签: django-templates django-forms

我有一个显示过滤器表单的模板,下面是一个结果记录列表。我将表单绑定到请求,以便过滤器表单将自己设置为返回结果时用户提交的选项。

我也使用分页。使用分页文档中的代码意味着当用户单击下一页时,表单数据将丢失。

以这种方式处理分页和过滤的最佳方法是什么?

  • 将查询字符串传递给分页链接。
  • 将分页链接更改为表单按钮,因此同时提交过滤器表单,但这假定用户没有使用过滤器选项。
  • 如上所述,但原始数据为隐藏字段。

ALJ

1 个答案:

答案 0 :(得分:2)

如果您不介意稍微调整一下URL,可以将过滤器选项直接嵌入到URL中。这实际上具有使搜索选项可收藏的非常好的附带好处。因此,当用户点击分页上的下一个/上一个按钮时,所有信息都将从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

有些情况下,使用这样的解决方案并不适用,但我不知道更多关于您的具体情况,我不能说。

希望这有帮助!

相关问题