ZetCode

Django Debug Toolbar

last modified November 21, 2026 Python 3.15

The Django Debug Toolbar is a third-party package that adds a panel to every HTML page of a project in development. It shows what happened while the page was built: the SQL queries and their duration, the templates and their context, the settings, the headers, the cache calls, the signals, and more. Its best known use is finding pages that run far more queries than needed. In this article we install the toolbar as a development dependency, look at when it appears and what its panels report, find and fix an N+1 problem in the SQL panel, inspect a JSON request, and keep the toolbar out of production and tests. The examples use Django 6.1, django-debug-toolbar 8.0, and Python 3.15.

The example project

The project is created with uv; the steps are explained in Django introduction. The commands below create a project directory, install Django, generate the project with the configuration package config, start the app blog, and create the folder demos for demo scripts.

$ mkdir debugtoolbar
$ cd debugtoolbar
$ uv init --bare
$ uv add django
$ uv add --dev django-debug-toolbar
$ uv run django-admin startproject config .
$ uv run python manage.py startapp blog
$ mkdir demos

The trailing dot in startproject config . creates manage.py and the config package in the current directory instead of one level deeper. The option --dev of uv add puts the toolbar into the development dependency group instead of the dependencies of the project; we come back to that at the end. A new app is ignored by Django until it is listed in INSTALLED_APPS, so we add the app to the list in config/settings.py; the other entries are generated by startproject.

config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]

The listings in this article are of two kinds. A listing with a solid blue border and the label Project file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed amber border and the label Demo script is a small helper in the demos folder; it sets up Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are not part of the application; we run one from the project directory with uv run python -m demos.name.

The blog has authors, tags, and posts. Each post has one author and several tags.

blog/models.py
from django.db import models


class Author(models.Model):
    name = models.CharField(max_length=60)

    def __str__(self):
        return self.name


class Tag(models.Model):
    name = models.CharField(max_length=30, unique=True)

    def __str__(self):
        return self.name


class Post(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='posts')
    tags = models.ManyToManyField(Tag, related_name='posts')
    published = models.DateField()

    class Meta:
        ordering = ['-published']

    def __str__(self):
        return self.title

We create the tables.

$ uv run python manage.py makemigrations blog
Migrations for 'blog':
  blog/migrations/0001_initial.py
    + Create model Author
    + Create model Tag
    + Create model Post
$ uv run python manage.py migrate | tail -n 2
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK

The script seed.py creates four authors, five tags, and twenty posts with two tags each. It deletes the old data first, so it can be run again.

demos/seed.py
import os
from datetime import date, timedelta

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from blog.models import Author, Post, Tag

Post.objects.all().delete()
Author.objects.all().delete()
Tag.objects.all().delete()

authors = [Author.objects.create(name=name) for name in ['Alice', 'Bob', 'Carol', 'Dave']]
tags = [Tag.objects.create(name=name) for name in ['python', 'django', 'sql', 'testing', 'web']]

start = date(2026, 1, 5)
for number in range(1, 21):
    post = Post.objects.create(title=f'Post number {number}', author=authors[number % 4],
                               published=start + timedelta(weeks=number))
    post.tags.set([tags[number % 5], tags[(number + 2) % 5]])

print('authors:', Author.objects.count(), 'tags:', Tag.objects.count(), 'posts:', Post.objects.count())

The database now has the data for the rest of the article.

$ uv run python -m demos.seed
authors: 4 tags: 5 posts: 20

A page with a hidden problem

The view post_list renders the posts, and post_api returns their titles and authors as JSON. Both look innocent.

blog/views.py
from django.http import JsonResponse
from django.shortcuts import render

from .models import Post


def post_list(request):
    posts = Post.objects.all()
    return render(request, 'blog/post_list.html', {'posts': posts})


def post_api(request):
    data = [{'title': post.title, 'author': post.author.name} for post in Post.objects.all()]
    return JsonResponse({'posts': data})

The template prints each post with the name of its author and its tags. The expressions post.author.name and post.tags.all follow relations, and each of them runs a query when it is evaluated.

blog/templates/blog/post_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Posts</title>
</head>
<body>
<h1>Posts</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }} by {{ post.author.name }}
  ({% for tag in post.tags.all %}{{ tag.name }}{% if not forloop.last %}, {% endif %}{% endfor %})</li>
{% endfor %}
</ul>
</body>
</html>

The URL configuration of the app connects the two views.

blog/urls.py
from django.urls import path

from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
    path('api/', views.post_api, name='post_api'),
]

The project includes the URLs of the app under /posts/.

config/urls.py
from django.urls import include, path

urlpatterns = [
    path('posts/', include('blog.urls')),
]

We start the development server.

$ uv run python manage.py runserver

The page works, and nothing in the output suggests that something is wrong.

$ curl -s localhost:8000/posts/ | head -n 14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Posts</title>
</head>
<body>
<h1>Posts</h1>
<ul>

<li>Post number 20 by Alice
  (python, sql)</li>

<li>Post number 19 by Dave

Installing the toolbar

The toolbar needs three changes in the settings. The app debug_toolbar provides the templates and static files. The middleware collects the data of each request and inserts the toolbar into HTML responses; it should come as early as possible in MIDDLEWARE, but after any middleware that encodes the response, such as GZipMiddleware. INTERNAL_IPS lists the addresses of the clients that may see the toolbar.

config/settings.py (toolbar)
INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
    'blog',
    'debug_toolbar',
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    ...
]

...

INTERNAL_IPS = ['127.0.0.1']

The toolbar loads the content of its panels from its own views, which debug_toolbar_urls() adds under the prefix __debug__/. The function returns an empty list when DEBUG is false.

config/urls.py
from debug_toolbar.toolbar import debug_toolbar_urls
from django.urls import include, path

urlpatterns = [
    path('posts/', include('blog.urls')),
] + debug_toolbar_urls()

The file pyproject.toml shows the toolbar in the group dev, separate from Django. The toolbar registers system checks that report a wrong installation, such as a missing middleware; our setup passes them.

$ cat pyproject.toml
[project]
name = "debugtoolbar"
version = "0.1.0"
requires-python = ">=3.15"
dependencies = [
    "django>=6.1.3",
]

[dependency-groups]
dev = [
    "django-debug-toolbar>=8.0.0",
]
$ uv run python manage.py check
System check identified no issues (0 silenced).

The toolbar in the browser

After restarting the server and reloading http://127.0.0.1:8000/posts/, the toolbar appears at the right side of the page. Each item is a panel, with a short summary below its name; a click on the name opens the panel, and the checkbox turns the panel off for the following requests. The button Hide collapses the toolbar into a small tab.

The Debug Toolbar on the list of posts
Figure: The Debug Toolbar next to the list of posts

The SQL panel already reveals the problem: 41 queries for a list of twenty posts. With curl we can see what the middleware has done. The HTML page has grown to about 800 lines because the toolbar is appended before </body>, inside a <template> with a shadow root, which keeps the styles of the toolbar and of the page apart. The JSON response is unchanged.

$ curl -s localhost:8000/posts/ | wc -l
804
$ curl -s localhost:8000/posts/ | grep -n -A 3 'djDebugRoot'
73:<div id="djDebugRoot" >
74-  <template shadowrootmode="open">
75-
76-    <link rel="stylesheet" href="/static/debug_toolbar/css/print.css" media="print">
$ curl -s localhost:8000/posts/api/ | head -c 120; echo
{"posts": [{"title": "Post number 20", "author": "Alice"}, {"title": "Post number 19", "author": "Dave"}, {"title": "Pos

When the toolbar is shown

The middleware asks the function in the option SHOW_TOOLBAR_CALLBACK whether to show the toolbar. The default function returns true only when DEBUG is true and the address of the client, REMOTE_ADDR, is in INTERNAL_IPS. The toolbar is then inserted only into responses with the type text/html that contain the closing </body> tag. The demo script checks these conditions with the test client, which sends requests from the address 127.0.0.1 unless told otherwise.

demos/visible.py
import os

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from django.test import Client, override_settings
from django.test.utils import setup_test_environment

setup_test_environment()


def toolbar(response):
    return 'yes' if b'id="djDebugRoot"' in response.content else 'no'


client = Client()
print('HTML page from 127.0.0.1:', toolbar(client.get('/posts/')))
print('HTML page from 10.0.0.7: ', toolbar(client.get('/posts/', REMOTE_ADDR='10.0.0.7')))
print('JSON from 127.0.0.1:     ', toolbar(client.get('/posts/api/')))

with override_settings(DEBUG=False, ALLOWED_HOSTS=['testserver']):
    print('HTML page, DEBUG off:    ', toolbar(client.get('/posts/')))

Only the HTML page requested from an internal address with DEBUG on has the toolbar. In Docker the requests come from the address of the Docker gateway, not from 127.0.0.1; for that case the package has the callback debug_toolbar.middleware.show_toolbar_with_docker, which can be set in the dictionary DEBUG_TOOLBAR_CONFIG.

$ uv run python -m demos.visible
HTML page from 127.0.0.1: yes
HTML page from 10.0.0.7:  no
JSON from 127.0.0.1:      no
HTML page, DEBUG off:     no

The panels

The demo script requests the list of posts and prints the identifier of each panel, whether it is enabled, and the summary from the toolbar's HTML.

demos/panels.py
import html
import os
import re

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from django.test import Client
from django.test.utils import setup_test_environment

setup_test_environment()

page = Client().get('/posts/').content.decode()
for item in re.findall(r'<li id="djdt-(.*?)</li>', page, re.S):
    panel = item.split('"')[0]
    enabled = 'checked' in item.split('>')[1]
    summary = re.search(r'<small>(.*?)</small>', item)
    print(f'{panel:17} {"on " if enabled else "off"} {html.unescape(summary[1]) if summary else ""}')

The History panel lists the recent requests, Versions the installed packages, Time the CPU and total time of the request, and Settings and Headers the settings and the HTTP headers. Request shows the view and the GET, POST, cookie, and session data; SQL the queries; Static files the files found by the finders; Templates the rendered templates with their context; Alerts common problems in the page, such as a form with a file field but without the right encoding; Cache the calls of the cache API; Signals the connected receivers; and Tasks the background tasks enqueued with the tasks framework of Django. The panels Redirects, which stops at each redirect to show the toolbar, and Profiling, which profiles the view with cProfile, are off by default and can be enabled with their checkbox or with the option DISABLE_PANELS. The list of panels can be changed with the setting DEBUG_TOOLBAR_PANELS.

$ uv run python -m demos.panels
HistoryPanel      on  /posts/
VersionsPanel     on  Django 6.1.3
TimerPanel        on  CPU: 635.47ms (84.73ms)
SettingsPanel     on
HeadersPanel      on
RequestPanel      on  post_list
SQLPanel          on  41 queries in 2.18ms
StaticFilesPanel  on  0 files used
TemplatesPanel    on  blog/post_list.html
AlertsPanel       on
CachePanel        on  0 calls in 0.00ms
SignalsPanel      on  35 receivers of 15 signals
TasksPanel        on  0 tasks
CommunityPanel    on
RedirectsPanel    off
ProfilingPanel    off

Finding N+1 queries in the SQL panel

The SQL panel lists every query with its time and the place in the code or template where it was run. The summary at the top says 41 queries including 40 similar and 20 duplicates. Queries are similar when they have the same SQL with different parameters, and duplicates when also the parameters are the same. Each query has a coloured mark of its group, and the buttons Sel and Expl run the query again or show its query plan.

The SQL panel of the Debug Toolbar
Figure: The SQL panel with similar and duplicated queries

The same data can be read from the toolbar's store in a script. The method DebugToolbar.fetch() returns the stored toolbar of a request, and the SQL panel's statistics contain the queries with their raw SQL and the numbers of similar and duplicated queries. The script groups the queries by their SQL.

demos/sqlpanel.py
import os
import re
from collections import Counter

import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()

from debug_toolbar.toolbar import DebugToolbar
from django.test import Client
from django.test.utils import setup_test_environment

setup_test_environment()

page = Client().get('/posts/').content.decode()
request_id = re.search(r'data-request-id="(\w+)"', page).group(1)
stats = DebugToolbar.fetch(request_id).get_panel_by_id('SQLPanel').get_stats()

queries = stats['queries']
print(f'{len(queries)} queries in {stats["sql_time"]:.2f} ms')
shapes = Counter(query['raw_sql'] for query in queries)
for sql, count in shapes.items():
    first = next(query for query in queries if query['raw_sql'] == sql)
    print(f'{count:2}x  similar={first.get("similar_count", 0):2}  '
          f'duplicates={first.get("duplicate_count", 0):2}  {sql[:70]}')

One query loads the posts. Then, for each of the twenty posts, the template loads the author and the tags: this is the N+1 problem, one query for the list and one more for every row. The author queries are also duplicates, because the four authors are loaded five times each. The longer the list, the slower the page, even though each query is fast.

$ uv run python -m demos.sqlpanel
41 queries in 2.17 ms
 1x  similar= 0  duplicates= 0  SELECT "blog_post"."id", "blog_post"."title", "blog_post"."author_id",
20x  similar=20  duplicates= 5  SELECT "blog_author"."id", "blog_author"."name" FROM "blog_author" WHE
20x  similar=20  duplicates= 0  SELECT "blog_tag"."id", "blog_tag"."name" FROM "blog_tag" INNER JOIN "

Fixing the queries

The fix is to load the related objects together with the posts. select_related('author') joins the table of authors to the query of the posts, and prefetch_related('tags') loads the tags of all posts in one additional query and distributes them in Python. These methods are explained in Django query performance. The JSON view uses the author as well, so it gets select_related too; the template does not change.

blog/views.py
from django.http import JsonResponse
from django.shortcuts import render

from .models import Post


def post_list(request):
    posts = Post.objects.select_related('author').prefetch_related('tags')
    return render(request, 'blog/post_list.html', {'posts': posts})


def post_api(request):
    posts = Post.objects.select_related('author')
    data = [{'title': post.title, 'author': post.author.name} for post in posts]
    return JsonResponse({'posts': data})

After reloading the page the SQL panel shows two queries without similar or duplicated ones.

$ uv run python -m demos.sqlpanel
2 queries in 0.40 ms
 1x  similar= 0  duplicates= 0  SELECT "blog_post"."id", "blog_post"."title", "blog_post"."author_id",
 1x  similar= 0  duplicates= 0  SELECT ("blog_post_tags"."post_id") AS "_prefetch_related_val_post_id"
$ uv run python -m demos.panels | grep SQL
SQLPanel          on  2 queries in 0.40ms

Requests without HTML

The JSON view has no page where the toolbar could appear, but the middleware records its data anyway. The History panel of any later HTML page lists the recent requests of the browser, here the API, the favicon.ico that the browser asks for, and the list of posts. The button Switch loads the data of a request into the toolbar, so the SQL panel of the API can be inspected as well. The store keeps the last 25 requests (the option RESULTS_CACHE_SIZE). For pages that load data with JavaScript, the option UPDATE_ON_FETCH makes the toolbar switch to each new fetch request automatically.

The History panel of the Debug Toolbar
Figure: The History panel with the API request

Development dependencies in production

In production the project is installed without the development group, for example with uv sync --no-dev, so the toolbar is not there. Note that uv run --no-dev would not help in this test: uv run does not remove packages that are already installed. With the settings and URLs as they are, Django cannot even start, because the settings name an app that cannot be imported. The option --no-sync keeps uv run from installing the group again.

$ uv sync --no-dev
Resolved 6 packages in 0.71ms
Uninstalled 1 package in 4ms
 - django-debug-toolbar==8.0.0
$ uv run --no-sync python manage.py check 2>&1 | tail -n 3
  File "<frozen importlib._bootstrap>", line 1353, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1242, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'debug_toolbar'

Loading the toolbar conditionally

The settings read DEBUG from an environment variable (see Django settings and environment) and add the toolbar only when DEBUG is on and the command is not test. The lines that added the toolbar to INSTALLED_APPS and MIDDLEWARE before are removed, and the block goes to the end of the file.

config/settings.py (conditional toolbar)
import os
import sys
from pathlib import Path

...

DEBUG = os.environ.get('DJANGO_DEBUG', '1') == '1'

...

# The debug toolbar is a development dependency: use it only with DEBUG on
# and keep it out of the tests.
if DEBUG and 'test' not in sys.argv:
    INSTALLED_APPS += ['debug_toolbar']
    MIDDLEWARE.insert(0, 'debug_toolbar.middleware.DebugToolbarMiddleware')
    INTERNAL_IPS = ['127.0.0.1']

The URL configuration imports the toolbar only when the app is installed.

config/urls.py
from django.conf import settings
from django.urls import include, path

urlpatterns = [
    path('posts/', include('blog.urls')),
]

if 'debug_toolbar' in settings.INSTALLED_APPS:
    from debug_toolbar.toolbar import debug_toolbar_urls

    urlpatterns += debug_toolbar_urls()

Now the production configuration, with DJANGO_DEBUG=0, passes the checks without the toolbar. With DEBUG on, the toolbar is still required, which is what we want in development. uv sync installs the development group again, and the toolbar is back.

$ DJANGO_DEBUG=0 uv run --no-sync python manage.py check
System check identified no issues (0 silenced).
$ uv run --no-sync python manage.py check 2>&1 | tail -n 1
ModuleNotFoundError: No module named 'debug_toolbar'
$ uv sync
Resolved 6 packages in 0.69ms
Installed 1 package in 3ms
 + django-debug-toolbar==8.0.0
$ uv run python manage.py check
System check identified no issues (0 silenced).
$ uv run python -m demos.panels | grep SQL
SQLPanel          on  2 queries in 0.41ms

Testing the number of queries

The test runner sets DEBUG to false, so the toolbar would not be shown in tests anyway; thanks to the condition it is not even loaded. The toolbar helps to find a problem once, and a test keeps it fixed. assertNumQueries() fails when a block runs a different number of queries, so a later change of the template that brings back the N+1 queries is caught.

blog/tests.py
from datetime import date

from django.test import TestCase

from .models import Author, Post, Tag


class PostListTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        author = Author.objects.create(name='Alice')
        tag = Tag.objects.create(name='django')
        for number in range(5):
            post = Post.objects.create(title=f'Post {number}', author=author,
                                       published=date(2026, 1, number + 1))
            post.tags.add(tag)

    def test_list_uses_two_queries(self):
        with self.assertNumQueries(2):
            response = self.client.get('/posts/')
        self.assertContains(response, 'Post 4 by Alice')
        self.assertNotContains(response, 'djDebug')

    def test_api_uses_one_query(self):
        with self.assertNumQueries(1):
            response = self.client.get('/posts/api/')
        self.assertEqual(len(response.json()['posts']), 5)

Both tests pass. The list makes two queries whatever the number of posts, and the API one.

$ uv run python manage.py test 2>&1
Found 2 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..
----------------------------------------------------------------------
Ran 2 tests in 0.008s

OK
Destroying test database for alias 'default'...

Source

Django Debug Toolbar documentation

Django Debug Toolbar: Panels

uv documentation: Development dependencies

In this article we have installed the Django Debug Toolbar as a development dependency, looked at when it is shown and what its panels report, found an N+1 problem with duplicated queries in the SQL panel and fixed it, inspected a JSON request with the history panel, kept the toolbar out of production and tests, and locked in the fix with a test. Related articles are Django query performance, Django logging, and Django settings and environment.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Django tutorials.