How to disable Django Debug Toolbar while rendering a template?

I'm using Django Debug Toolbar in my development environment, and it's been very helpful for debugging. However, I want to disable it when rendering a specific template. Is there a way to conditionally disable the debug toolbar for certain views or templates?

Here’s what I’ve tried so far:

  • Using settings.DEBUG: I know that the toolbar is only shown when DEBUG = True in settings.py, but I don't want to disable it for the entire project, just for specific views or templates.
  • Template Context: I also considered passing a context variable to the template to control the toolbar's visibility, but I’m not sure how to integrate this with the toolbar's behavior.

Here’s a simplified version of my view:

from django.shortcuts import render

def my_view(request):
    context = {'some_data': 'data'}
    return render(request, 'my_template.html', context)

And in my settings.py:

DEBUG = True

if DEBUG:
    INSTALLED_APPS += ['debug_toolbar']
    MIDDLEWARE += ['debug_toolbar.middleware.DebugToolbarMiddleware']

django_debug_toolbar version is 3.8.1

Is there a way to disable the Django Debug Toolbar specifically for this view or template?

You can specify a SHOW_TOOLBAR_CALLBACK, that determines if you want to show the toolbar for a certain request:

DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': 'app_name.debug.show_toolbar',
}

and then check the request path:

# app_name/debug.py

def show_toolbar(request):
    # The toolbar renders correctly except for my view.
    return request.path != '/path/to/my-view/'

or we can try to resolve it first:

# app_name/debug.py

from django.urls import resolve

def show_toolbar(request):
    return resolve(request.path).func is not my_view
Вернуться на верх