S
S
Sergey Ganzhela2016-10-21 16:27:29
Django
Sergey Ganzhela, 2016-10-21 16:27:29

Setting up pagination in a django project?

Hey!
Please tell me how to properly organize pagination in a django project so that it is possible for the client to set the desired number of elements on the page

class BaseProductsList(generic.ListView):

    context_object_name = 'products'
    template_name = 'product.html'

    def get_context_data(self, **kwargs):
        context = super(BaseProductsList, self).get_context_data()
        context['categories'] = Category.objects.prefetch_related('subcategory').all().order_by('name')
        return context

    def get_queryset(self):
        qs = Product.objects.filter(available=1)
        return qs

    def get(self, request, **kwargs):
        self.paginate_by = self.request.GET.get('show', 8)
        return super(BaseProductsList, self).get(request, **kwargs)

and client side element
<select id="input-limit" class="form-control">
              <option value="4" selected="selected">4</option>
              <option value="8">8</option>
              <option value="25">25</option>
            </select>

in the view I tried to override the get method and pull it out of the request, the value was transferred by ajax, there is no error, but the number does not change!
Tell me how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-10-21
@Sergiy_Hanzhela

https://github.com/django/django/blob/3c447b108ac7...

# 

    def get_paginate_by(self, queryset):
        """
        Get the number of items to paginate by, or ``None`` for no pagination.
        """
        try:
            self.paginate_by = int(
               self.request.GET.get('paginate_by', self.paginate_by))
        except ValueError:
            logger.error('Some stupid person use not int for paginate_by')

        return self.paginate_by

<form method="get">
  <select id="input-limit" name="paginate_by" class="form-control">
    <option value="4" selected="selected">4</option>
    <option value="8">8</option>
    <option value="25">25</option>
  </select>
  <button type="submit">Paginate by</button>
</form>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question