from django.http import HttpResponse
import simplejson
class AJAXFallbackView(View):
# views (get, post, etc) must return (context, template) instead of rendering it themselves
# similar to auto_render
valid_json_start = ['"', '[', '{']
valid_json_end = ['"', ']', '}']
def dispatch(self, request, *args, **kwargs):
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
self.request = request
self.args = args
self.kwargs = kwargs
template, ctx = handler(request, *args, **kwargs)
return self.render(template, ctx)
def render(self, template, context):
if self.format=='json':
json = simplejson.dumps(context)
callback = self.request.GET.get('callback')
if callback:
if json[0] not in self.valid_json_start or json[-1] not in self.valid_json_end:
json = ''.join(['"',json,'"'])
return HTTPResponse('%s(%s)' % (callback,json),mimetype='application/javascript')
return HTTPResponse(json, mimetype='application/json')
else:
return render_to_response(template, context, RequestContext(self.request))
##############################
#sample view
class MyListView(AJAXFallbackView):
def get(self, request):
return 'index.html',{'models':MyModel.objects.all()}
Comments