Login

Class-Based AJAX fallback view

Author:
fahhem
Posted:
January 24, 2011
Language:
Python
Version:
1.2
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. "Magic Link" Management Command by webology 3 months ago
  2. Closest ORM models to a latitude/longitude point by simonw 3 months ago
  3. Log the time taken to execute each DB query by kennyx46 3 months ago
  4. django database snippet by ItsRLuo 3 months, 1 week ago
  5. Serialize a model instance by chriswedgwood 4 months ago

Comments

Please login first before commenting.