使用Generic ListView进行动态分页 [英] Dynamic pagination using Generic ListView

查看:165
本文介绍了使用Generic ListView进行动态分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求:用户应该能够选择每个页面他想在助理列表中看到多少个项目。我在Django 1.4中使用通用的ListView。

I have a requirement that a user should be able to choose how many items per page he wants to see in a list of assistants. I am using a generic ListView in Django 1.4.

我的代码在这个变化之前看起来像这样:

My code before this change looks like this:

Class AssistantList(ListView):
    template_name = "register/assistant_list.html"
    context_object_name = 'assistant_list'
    paginate_by = 25

如何根据用户的选择动态设置paginate_by,而不是像上面那样对其进行硬编码?

How can I set the paginate_by dynamically based on the user's selection instead of hardcoding it as above?

推荐答案

我刚刚不得不这样做。您可以覆盖get_paginate_by函数来获取查询字符串参数。这是一个基本的例子。

I just recently had to do this. You can override the get_paginate_by function to grab a query string parameter. Here's a basic example.

Class AssistantList(ListView):
    template_name = "register/assistant_list.html"
    context_object_name = 'assistant_list'
    paginate_by = 25

    def get_paginate_by(self, queryset):
        """
        Paginate by specified value in querystring, or use default class property value.
        """
        return self.request.GET.get('paginate_by', self.paginate_by)

然后在我们的html中,我们有一个下拉列表选择,用户可以选择要查看的项目数。

Then in our html we have a dropdown selection where the user can choose the number of items to view.

<form action="." method="get">
    <select name="paginate_by">
        <option>25</option>
        <option>50</option>
        <option>75</option>
        <option>100</option>
    </select>
</form>

我们添加了一些javascript以使其自动提交,您将需要将paginate_by传递给上下文,以便您可以确保它继续从页到页。

We added some javascript to make it auto-submit and you'll want to pass the paginate_by through to the context so you can make sure it continues to get passed from page to page.

这篇关于使用Generic ListView进行动态分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆