Class-Based AJAX fallback view

 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 2 years, 8 months ago
  2. Better Static Image Serving With Fallback by menendez 4 years ago
  3. Format transition middleware by limodou 7 years, 1 month ago
  4. Export Related as JSON Admin Action by johnboxall 4 years, 9 months ago
  5. JsonResponse by zakj 7 years ago

Comments

(Forgotten your password?)