UPDATE: See Peter’s comment below for a slightly revised (and better) version of this.
The Django Debug Toolbar is essential for developing Django applications but it comes short in one area – Ajax. There’s been progress over the last couple years but the latest pull request for a panel that supports Ajax has yet to be completed and merged. This leaves you pretty much in the dark when making XHR requests as the toolbar only works if the mimetype of the response is either
application/xhtml+xml and contains a closing
</body> tag (otherwise your XHR requests would be filled with a bunch of junk from the toolbar).
After digging around I stumbled upon this SO post which details a few solutions including using the following middleware:
|from django.conf import settings|
|View a JSON response in your browser as HTML|
|Useful for viewing stats using Django Debug Toolbar|
|This middleware should be place AFTER Django Debug Toolbar middleware|
|def process_response(self, request, response):|
|# not for production or production like environment|
|if not settings.DEBUG:|
|# do nothing for actual ajax requests|
|# only do something if this is a json response|
|if 'application/json' in response['Content-Type'].lower():|
|title = 'JSON as HTML Middleware for: %s' % request.get_full_path()|
|response.content = '<html><head><title>%s</title></head><body>%s</body></html>' % (title, response.content)|
|response['Content-Type'] = 'text/html'|
Add this middleware right after the debug toolbar in your settings (and ensure that it is only enabled for your dev environment) and then load an Ajax URL directly in a browser tab. The middleware simply detects that you’re not making this request as Ajax and wraps the response in some HTML which will activate the debug toolbar. Very handy.
It’s definitely a bit of a hack and doesn’t make working with posts very easy, but it’s better than nothing.