Returning JSON error when catching Django exception?
What we do on our project MapIt - https://github.com/mysociety/mapit - for doing this is to raise an Exception to a middleware, as you say, which then directly returns either an HTML template or a JSON object depending on the format provided by the request. You can view the code at https://github.com/mysociety/mapit/blob/master/mapit/middleware/view_error.py
In terms of additional headers, our output_json function sets the Content-Type on the response to 'application/json; charset=utf-8'.
For the 404 case, we have our own get_object_or_404 function that wraps get_object_or_404 and converts a Django Http404 exception into our own exception that will then correctly return JSON if appropriate to the request.
from django.shortcuts import get_object_or_404 as orig_get_object_or_404def get_object_or_404(klass, format='json', *args, **kwargs): try: return orig_get_object_or_404(klass, *args, **kwargs) except http.Http404, e: raise ViewException(format, str(e), 404)