If you're used to auto_render like I am (and think it's an awesome way to DRY code) and you want to support users with and without javascript enabled, this class is perfect.
You will need to provide the format requested, either through adding "(.format)?" at the end of the url or through some middleware, but once you've done so this class will take care of rendering through the given template for normal users, JSON or JSONP for AJAX users.
From fahhem.com and Recrec Labs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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()}
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.