0

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})

1 Answers1

2

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')
    # ...
]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • 1
    I don't recommend passing parameters to `as_view` for readability reasons, You don't have to look in **urls.py** to see your view logic, This should work 1000% as expected, But it's not a good practise. – Ahmed I. Elsayed Mar 28 '20 at 16:43
  • 1
    I tend to agree. Also, in a real project, such simple views are rare. On the other hand, where does the search for a view in a code base start, if not from the url ;-) I do use this pattern a bit for static `TemplateView` views that I only pass a template name. – user2390182 Mar 28 '20 at 16:46
  • I usually do the same – Ahmed I. Elsayed Mar 28 '20 at 17:18