Skip to content

Instantly share code, notes, and snippets.

@prestontimmons
Created January 31, 2012 15:43
Show Gist options
  • Save prestontimmons/1711148 to your computer and use it in GitHub Desktop.
Save prestontimmons/1711148 to your computer and use it in GitHub Desktop.
Django json_view decorator
from functools import wraps
from json import dumps
from django.http import HttpResponse
def json_view(view_func):
@wraps(view_func)
def inner(request, *args, **kwargs):
response = view_func(request, *args, **kwargs)
if request.GET.get("format") == "json" and hasattr(response, "context_data"):
return HttpResponse(
dumps(response.context_data, sort_keys=True),
mimetype="application/json",
)
return response
return inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment