Last active
May 12, 2025 12:33
-
-
Save fabiosussetto/c534d84cbbf7ab60b025 to your computer and use it in GitHub Desktop.
Enable Django toolbar for JSON responses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NonHtmlDebugToolbarMiddleware(object): | |
""" | |
The Django Debug Toolbar usually only works for views that return HTML. | |
This middleware wraps any JSON response in HTML if the request | |
has a 'debug' query parameter (e.g. http://localhost/foo?debug) | |
""" | |
@staticmethod | |
def process_response(request, response): | |
if request.GET.get('debug'): | |
if response['Content-Type'] == 'application/json': | |
content = json.dumps(json.loads(response.content), sort_keys=True, indent=2) | |
response = HttpResponse(u'<html><body><pre>{}</pre></body></html>'.format(content)) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@arbuckle Thanks for the updated version.
I added syntax highlighting and "if django debug toolbar is enabled" detection to make it even more useful. The updated version can be found here: https://gist.github.com/ulgens/73fe671d54eff80edb54a30e255c6a5f