Skip to content

Instantly share code, notes, and snippets.

@xpostudio4
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xpostudio4/8a78cd17026e9ac2d55b to your computer and use it in GitHub Desktop.
Save xpostudio4/8a78cd17026e9ac2d55b to your computer and use it in GitHub Desktop.
Helper functions and classes for default app folder in django.
"""
The purpose of this function files is to keep all the helpfull
functions constanlly used in a django base project.
"""
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def paginated_list(request, object_class, list_length, order=None, *args, **kwargs):
"""
The purpose of this function is to generate the list of all the
paginated elements to be displayed on the diferent pages.
keyword arguments:
object_class -- The object we'll be calling as a list
order -- should it be ordered by any variable
list_length -- How many elements we'll display on a single page
*args, **kwargs -- The filters when calling the objects.
"""
object_list = object_class.objects.filter(*args, **kwargs)
if order is not None:
object_list.order_by(order)
paginator = Paginator(object_list, list_length) #show 20 c per page
page = request.GET.get('page')
try:
objects = paginator.page(page)
except PageNotAnInteger:
#if the page is not an integer, deliver the first page.
objects = paginator.page(1)
except EmptyPage:
#if page is out range (e.g. 9999), deliver last page of results.
objects = paginator.page(paginator.num_pages)
return objects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment