user13080604
user13080604

Reputation:

Why is it not getting paginated?

I'm trying to develop a website, where I wrote a function based view, and now want to add pagination.I'm following the django documentation, but it's just not coming together. Can anyone help me please? my views.py:

from django.shortcuts import render, Http404
from django.http import HttpResponse
from .models import Product
from django.core.paginator import Paginator

def home(request):
    products = Product.objects.all()
    paginator = Paginator(products, 6)

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'index.html', {'products': products})

Upvotes: 0

Views: 85

Answers (1)

user2390182
user2390182

Reputation: 73498

First, you might want to convert the page parameter to int:

page_number = int(page_number)

Then, you still pass the original queryset to your template. To pass the paginated object list, do:

return render(request, 'index.html', {'products': page_obj.object_list})

Or even more useful, pass the page object:

return render(request, 'index.html', {'page_obj': page_obj})

That way, you have all information to access the object list, but also to build the next and previous links.

Yet more convenient, you can use the ListView class:

class HomeView(ListView):
    model = Product
    paginate_by = 6
    context_object_name = 'products'
    template_name = 'index.html'

Given you view code, you would not even have to override any of the default behaviour, so you could directly use the ListView in you urls:

urlpatterns = [
    # ...
    path('', ListView.as_view(model=Product, 
                              paginate_by=6, 
                              context_object_name='products', 
                              template_name='index.html'), name='index')
    # ...
]

Upvotes: 2

Related Questions