[Answered ]-Different number of records in django pagination pages

1👍

Firstly change your __init__ method in MyPaginator to fix the error:

from math import ceil


class MyPaginator(Paginator):
    
    def __init__(self, *args, **kw):
        self.deltafirst = kw.pop('deltafirst', 0)
        super().__init__(*args, **kw)
    
    def page(self, number):
        number = self.validate_number(number)
        if number == 1:
            bottom = 0
            top = self.per_page - self.deltafirst
        else:
            bottom = (number - 1) * self.per_page - self.deltafirst
            top = bottom + self.per_page
        if top + self.orphans >= self.count:
            top = self.count
        return Page(self.object_list[bottom:top], number, self)

    @property
    def num_pages(self):
        if self.count == 0 and not self.allow_empty_first_page:
            return 0
        count = max(self.count - self.per_page + self.deltafirst, 0)
        hits = max(0, count - self.orphans)
        return 1 + ceil(hits / self.per_page)

Next to make your view simpler instead of overriding get_context_data override get_paginator and also set deltafirst as a class attribute:

class NewsView(ListView):
    model = News
    template_name="mysite/news.html"
    paginate_by =  5
    paginator_class = MyPaginator
    deltafirst = 1
    
    def get_paginator(self, *args, **kwargs):
        if self.deltafirst:
            kwargs['deltafirst'] = self.deltafirst
        return super().get_paginator(*args, **kwargs)

Leave a comment