Skip to content

Instantly share code, notes, and snippets.

@carljm
Created March 27, 2011 18:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save carljm/889437 to your computer and use it in GitHub Desktop.
Save carljm/889437 to your computer and use it in GitHub Desktop.
An example of a decorator for a view that returns a TemplateResponse, modifying the template context before it is rendered.
def paginate(ctx_name):
"""
View decorator that handles pagination of a ListObject. Expects to find it
in the TemplateResponse context under the name ``ctx_name``.
This needs to not force delivery of the ListObject.
"""
def decorator(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
response = view_func(request, *args, **kwargs)
ctx = response.context_data
pagesize, pagenum = pagination.from_request(request)
ctx[ctx_name] = ctx[ctx_name].paginate(pagesize, pagenum)
# the lambda here makes Pager fetch the total result count
# lazily; another decorator might modify the result set yet.
ctx["pager"] = pagination.Pager(
lambda: ctx[ctx_name].totalResults, pagesize, pagenum)
return response
return _wrapped_view
return decorator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment