已解决:django 列表视图

列表视图的主要问题是它们难以使用并且容易混淆。

 with pagination

I am trying to create a listview with pagination in Django. I have tried the following code but it is not working:
<code>class MyListView(ListView):

    model = MyModel
    template_name = 'my_template.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['page'] = self.request.GET.get('page')

        return context

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)

        try:
            page = int(response.context['page']) - 1
            if page &lt; 0: page = 0  # first page is 1 not 0! (paginator bug?)
            response.context['previous'] = str(page) if page &gt; 0 else None  # None for first page! (paginator bug?)
            response.context['next']     = str(page + 2) if len(response.context['object_list']) == 10 else None  # None for last page! (paginator bug?)

        except KeyError: pass  # no 'page' in the context... means we're on the first one! (no previous!) or last one! (no next!) or something went wrong... just ignore it and don't add anything to the context then...

        return response    
</code>

此代码是带有分页的列表视图的基于类的视图。 前四行定义类、要使用的模型、要使用的模板和要使用的上下文数据。 接下来的四行定义了 get 方法和响应。 最后四行定义了 get_context_data 方法并返回上下文数据。

什么是列表视图

列表视图是 Django 中显示项目列表的小部件。

相关文章:

发表评论