Nalutas: django listview

Ang pangunahing problema sa mga listview ay mahirap gamitin at maaaring nakakalito.

 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>

Ang code na ito ay isang class-based na view para sa isang listview na may pagination. Tinutukoy ng unang apat na linya ang klase, ang modelong gagamitin, ang template na gagamitin, at ang data ng konteksto na gagamitin. Tinutukoy ng susunod na apat na linya ang get method at ang tugon. Tinutukoy ng huling apat na linya ang get_context_data method at ibinalik ang context data.

Ano ang listview

Ang listview ay isang widget sa Django na nagpapakita ng listahan ng mga item.

Kaugnay na mga post:

Mag-iwan ng komento