Debug Toolbar

Debug and optimize your Django application

🔧 What is Django Debug Toolbar?

Django Debug Toolbar is a powerful debugging tool that displays detailed information about your application's performance, SQL queries, templates, and more. It helps identify bottlenecks and optimize your Django code.


# Install Debug Toolbar
pip install django-debug-toolbar
                                    

Toolbar Features

🗄️

SQL Queries

View all database queries

Query Count Execution Time
⏱️

Performance

Measure page load times

CPU Time Memory Usage
📄

Templates

See which templates are used

Template Names Context Data
📊

Request Info

View request and response data

Headers Session Data

🔹 Install Debug Toolbar

Install Django Debug Toolbar using pip. This package adds a sidebar to your Django pages showing detailed debugging information during development.

# Install the package
pip install django-debug-toolbar

# Add to requirements.txt
echo "django-debug-toolbar" >> requirements.txt

Output:

✓ Successfully installed django-debug-toolbar-4.2.0

🔹 Configure Settings

Add Debug Toolbar to your Django settings. Include it in INSTALLED_APPS and MIDDLEWARE, and configure INTERNAL_IPS to enable the toolbar on localhost.

# settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'debug_toolbar',  # Add this
    'myapp',
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',  # Add this (near top)
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# Required for toolbar to show
INTERNAL_IPS = [
    '127.0.0.1',
]

🔹 Add URL Configuration

Include Debug Toolbar URLs in your project's URL configuration. This enables the toolbar's interactive features and panels in your development environment.

# urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]

# Add Debug Toolbar URLs (only in DEBUG mode)
if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        path('__debug__/', include(debug_toolbar.urls)),
    ] + urlpatterns

Important:

Debug Toolbar only works when DEBUG = True in settings.py

🔹 View SQL Queries

The SQL panel shows all database queries executed on a page. Use this to identify slow queries, duplicate queries, and optimize your database access patterns.

# views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
    # This will show in Debug Toolbar
    posts = Post.objects.all()
    
    # You can see how many queries this generates
    for post in posts:
        print(post.author.username)  # N+1 query problem!
    
    return render(request, 'posts.html', {'posts': posts})

SQL Panel Shows:

  • Total number of queries
  • Query execution time
  • Duplicate queries
  • Slow queries highlighted
  • Full SQL statements

🔹 Optimize with select_related

Use Debug Toolbar to identify N+1 query problems. The select_related method reduces database queries by fetching related objects in a single query.

# views.py - Before optimization
def post_list(request):
    posts = Post.objects.all()  # 1 query
    # Accessing post.author creates 1 query per post (N+1 problem)
    return render(request, 'posts.html', {'posts': posts})

# After optimization
def post_list(request):
    # Only 1 query total!
    posts = Post.objects.select_related('author').all()
    return render(request, 'posts.html', {'posts': posts})

Debug Toolbar Shows:

Before: 101 queries (1 + 100 for authors)

After: 1 query (optimized!)

🔹 Check Template Usage

The Templates panel shows which templates are rendered and what context variables are available. This helps debug template inheritance and context issues.

# views.py
def home(request):
    context = {
        'title': 'Home Page',
        'user': request.user,
        'posts': Post.objects.all()[:5]
    }
    return render(request, 'home.html', context)

Templates Panel Shows:

  • Template file paths
  • Template inheritance chain
  • Context variables and values
  • Template rendering time

🔹 Monitor Performance

Use the Timer panel to measure page load performance. It breaks down time spent in different parts of your application to identify bottlenecks.

Performance Metrics:

  • Total Time: Complete request/response cycle
  • SQL Time: Database query execution
  • CPU Time: Python code execution
  • Template Time: Template rendering
# Example: Slow view that needs optimization
def slow_view(request):
    import time
    time.sleep(2)  # Debug Toolbar will show this delay!
    
    posts = Post.objects.all()
    for post in posts:
        post.author.username  # N+1 queries visible in toolbar
    
    return render(request, 'posts.html', {'posts': posts})

🧠 Test Your Knowledge

What does Debug Toolbar help you identify?