0

i know how to implement pagination in class base views using ListView

class ProductListView(ListView):
       model = product
       template_name = 'products/product_list.html'  
       context_object_name = 'products'
       ordering = ['-pub_date']
       paginate_by = 5

but i don't know how to implement paginations in function base views. i read that we have to import Paginator for django.core.paginator and use it in functions base view like this paginator = Paginator(qs, 5) but it's not working.

    def Productlistview(request):
       qs = product.objects.all()
       location_search = request.GET.get('location')
       print(location_search)
       categories = request.GET.get('categories')
       price = request.GET.get('price')
       ordering = ['-pub_date']
       paginator = Paginator(qs, 5)
       if location_search != "" and location_search is not None:
              qs = qs.filter(location__contains=location_search)

     context = {
       'posts': qs
      }

    return render(request, "products/product_list.html", context)
bmons
  • 3,352
  • 2
  • 10
  • 18
Muzaffar
  • 51
  • 1
  • 7

1 Answers1

0

This is covered in the Pagination section of the documentation. You indeed use a paginator, but you still need to pass the page that you want to show. This is often done through a GET parameter, like for example page. Furthermore you should do the filtering and ordering before paginating.

def product_list_view(request):
    qs = product.objects.all()
    location_search = request.GET.get('location')
    print(location_search)
    categories = request.GET.get('categories')
    price = request.GET.get('price')
    if location_search:
        qs = qs.filter(location__contains=location_search)
    qs = qs.order_by('-pub_date')
    paginator = Paginator(qs, 5)
    page = p.page(request.GET.get('page'))
     context = {
       'posts': page
      }

    return render(request, "products/product_list.html", context)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555