Last Updated: September 27, 2019
·
20.59K
· julian-amaya

Returning JSON/JSONP from a Django view with a little decorator help

This is a decorator that helps creating a JSON response:

def json_response(func):
    """
    A decorator thats takes a view response and turns it
    into json. If a callback is added through GET or POST
    the response is JSONP.
    """
    def decorator(request, *args, **kwargs):
        objects = func(request, *args, **kwargs)
        if isinstance(objects, HttpResponse):
            return objects
        try:
            data = simplejson.dumps(objects)
            if 'callback' in request.REQUEST:
                # a jsonp response!
                data = '%s(%s);' % (request.REQUEST['callback'], data)
                return HttpResponse(data, "text/javascript")
        except:
            data = simplejson.dumps(str(objects))
        return HttpResponse(data, "application/json")
    return decorator

So in every view I now need a JSON/JSONP response I just use:

@json_response
def any_view(request):
    return {'this will be': 'JSON'}

You can also use it with arrays like:

@json_response
def any_view(request):
    return ['anything', 'serializable']

Or maybe with some models:

class MyModel(models.Model):
    name = models.CharField(max_length=150)
    other_att = models.TextField()

    def to_json_dict(self):
        return {'name': self.name}


@json_response
def any_view(request):
    return [mm.to_json_dict() for mm in MyModel.objects.all()]

If you call you make the call something like ** http://yourhost/the_url/?callback=fname ** then the response will be in JSONP format :)

(BTW, you can found the code and more decorators in https://github.com/julian-amaya/django-decorators )

3 Responses
Add your response

nice!

over 1 year ago ·

Thanks, you really save my live with this

over 1 year ago ·

Thanks, this helped loads

over 1 year ago ·