Source code for scripts.my_shortcuts

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.utils import simplejson
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
#from django.core.serializers.json import DateTimeAwareJSONEncoder

[docs]def render_to_json(*args, **kwargs): """ Use this instead of render_to_response if you want to use JSON information. This will stop IE from caching the results and make sure that browsers treat the data as JSON rather than HTML. From http://djangosnippets.org/snippets/468/ """ response = render_to_response(*args, **kwargs) response['mimetype'] = "text/javascript" response['Pragma'] = "no cache" response['Cache-Control'] = "no-cache, must-revalidate" return response
[docs]def render_to_hxr_response(*args, **kwargs): """ Use this instead of render_to_response if you want to access using an XMLHttpRequest This is because ipads return a response status of 0 (error) when it's cached content, meaning that it just doesn't work. """ response = render_to_response(*args, **kwargs) response['mimetype'] = "text/html" response['Pragma'] = "no cache" response['Cache-Control'] = "no-cache, must-revalidate" return response
[docs]def HttpResponseJson(biggus_dictus): """ My own function this one. But it's based on the above render_to_json. Effectively you pass it a dictionary/list thing and it renders a JSON object over HTTP. "I have a gweat fwiend in Wome called Biggus Dickus" And this takes a big dict... or a small dict. Or a list. It doesn't discriminate as long as the object is serializable as JSON. I'd like to write something that loops through the queryset and renders as a JSON object, regardless of type, so splitting datetimes into datetimes and all subqueryset objects into dicts/lists too. But that might be one for another time. """ resp = HttpResponse(simplejson.dumps(biggus_dictus), mimetype='text/javascript') resp['Pragma'] = "no-cache" resp['Cache-Control'] = "no-cache must-revalidate proxy-revalidate" return resp
[docs]def paginate(the_list, num, page): """ Simple function to paginate a list Pass the queryset, the number of objects to return and details of the current page and it returns the paginated list of objects, e.g.:: groups = paginate(group_list, 25, request.GET.get('page')) This means you don't need to do this for all paginated pages """ paginator = Paginator(the_list, num) if page is None: page = 1 try: objs = paginator.page(page) except PageNotAnInteger: objs = paginator.page(1) except EmptyPage: objs = paginator.page(paginator.num_pages) return objs

Project Versions