Login

Class-Based AJAX fallback view

Author:
fahhem
Posted:
January 24, 2011
Language:
Python
Version:
1.2
Tags:
ajax view json class fallback class-based
Score:
0 (after 0 ratings)

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

  1. Generic view mixing that allows output to JSON, HTML, HTML SNIPPETS by danielsokolowski 3 years, 8 months ago
  2. Better Static Image Serving With Fallback by menendez 5 years ago
  3. Format transition middleware by limodou 8 years, 1 month ago
  4. Export Related as JSON Admin Action by johnboxall 5 years, 9 months ago
  5. JsonResponse by zakj 7 years, 12 months ago

Comments

Please login first before commenting.