Login

Extend generic view object_list to support paginate_by via cookies

Author:
kersurk
Posted:
January 19, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

You can use this view to have a possibility to use ?paginate_by=x on your generic lists.

Example usage in urls.py:

url('^list/', object_list_with_paginate_by, {'queryset': Invoice.objects.all(), 'template_name': 'invoices/list.html', 'paginate_by': 10}, 'invoices.list')

10 is the default objects count per page.

For the first time parameter paginate_by is set in URL, we have to get it straight from there. If the parameter is set, then also set the cookie for later requests without the parameter If the parameter is not set, then we try the cookie or default value

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def object_list_with_paginate_by(request, **kwargs):
  is_valid_paginate_by_parameter = True
  try:
    paginate_by = int(request.GET.get('paginate_by', 0))
  except ValueError:
    paginate_by = 0

  if not paginate_by: #don't make it into else!
    is_valid_paginate_by_parameter = False
    try:
      paginate_by = int(request.COOKIES.get('paginate_by', 0))
    except ValueError:
      paginate_by = 0

  if paginate_by: #don't make it into else!
    kwargs['paginate_by'] = paginate_by

  response = object_list(request, **kwargs)

  if is_valid_paginate_by_parameter:
    response.set_cookie('paginate_by', paginate_by)

  return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.