解決済み: 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>

このコードは、ページネーションを使用したリストビューのクラス ベースのビューです。 最初の XNUMX 行は、クラス、使用するモデル、使用するテンプレート、および使用するコンテキスト データを定義します。 次の XNUMX 行は、get メソッドと応答を定義します。 最後の XNUMX 行では、get_context_data メソッドを定義し、コンテキスト データを返します。

リストビューとは

リストビューは、アイテムのリストを表示する Django のウィジェットです。

関連記事:

コメント