Skip to content

Instantly share code, notes, and snippets.

@zgohr
Created December 10, 2013 22:23
Show Gist options
  • Save zgohr/7901403 to your computer and use it in GitHub Desktop.
Save zgohr/7901403 to your computer and use it in GitHub Desktop.
Basic django class based JSON view that can handle JSONP callbacks
from django.http import HttpResponse
from django.views import generic
import json
class JSONView(generic.View):
callback_parameter = 'callback'
def get_json_data(self, request, *args, **kwargs):
"""
Implement this function to return the object to be serialized
"""
raise NotImplementedError
def get(self, request, *args, **kwargs):
data = self.get_json_data(request, *args, **kwargs)
callback = request.GET.get(self.callback_parameter)
if callback:
response = HttpResponse("%s(%s);" % (callback, json.dumps(data)),
content_type='text/javascript')
else:
response = HttpResponse(json.dumps(data),
content_type='application/json')
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment