Skip to content

Instantly share code, notes, and snippets.

@fabiosussetto
Last active December 2, 2023 01:11
Show Gist options
  • Save fabiosussetto/c534d84cbbf7ab60b025 to your computer and use it in GitHub Desktop.
Save fabiosussetto/c534d84cbbf7ab60b025 to your computer and use it in GitHub Desktop.
Enable Django toolbar for JSON responses
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
@muralikg
Copy link

Save me a lot of trouble. Thanks!

@Tobeyforce
Copy link

I believe this doesn't work anymore due to django changing the way middlewares should be structured :)

@BakrFrag
Copy link

Dears ,
By default Django Debug Toolbar needs html content to display upon , good news is that DRF comes with browsable api build in , by default renderers classes in Django is JSON & Browsable API , i totally sure you modify renders classes attributes as per viewset or generic function and override defaults , so add it again and it will works fine

from rest_framework.renderers import BrowsableAPIRenderer

them add it as

renderer_classes = [ .... ,BrowsableAPIRenderer]

with viewsets or generic views

@arbuckle
Copy link

Here's an updated version that works with Django 4.2.

import json
from django.http import HttpResponse

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)

    adapted from:
    https://gist.github.com/fabiosussetto/c534d84cbbf7ab60b025
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if request.GET.get('debug', None) is not None:
            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