Django Debug Toolbar
Django Debug Toolbar
Diagnosing performance issues in Django requires visibility into what occurs under the hood on every HTTP request. The Django Debug Toolbar (DDT) is a configurable sidebar that attaches to rendered HTML pages during local development, displaying detailed metrics on SQL queries executed, cache hits/misses, HTTP headers, template rendering times, and memory consumption.
1. Installing and Configuring Django Debug Toolbar
Configuration in settings.py:
Configuration in config/urls.py:
2. The SQL Panel: Catching N+1 Queries
The most powerful panel in DDT is the SQL Panel:
┌─────────────────────────────────────────────────────────────┐ │ Django Debug Toolbar - SQL Queries │ ├─────────────────────────────────────────────────────────────┤ │ Total Queries: 104 | Time: 182.40ms | Duplicates: 101 │ ├─────────────────────────────────────────────────────────────┤ │ 1. SELECT * FROM enterprise_articles (1.2ms) │ │ 2. SELECT * FROM auth_user WHERE id = 1 (0.8ms) [DUPLICATE] │ │ 3. SELECT * FROM auth_user WHERE id = 1 (0.9ms) [DUPLICATE] │ │ 4. SELECT * FROM auth_user WHERE id = 1 (0.8ms) [DUPLICATE] │ │ ... │ └─────────────────────────────────────────────────────────────┘
- Duplicate Queries Badge: Highlights duplicate queries in red/magenta, instantly alerting you to an N+1 query bug!
EXPLAINandTRACE: ClickingEXPLAINon any query shows the database execution plan, showing if a full table scan occurred due to a missing index.
3. Other Core Debug Panels
- Time Panel: Breaks down CPU execution time between Python code, template compilation, and database queries.
- Templates Panel: Lists every template and partial (
base.html,_card.html) rendered on the page, along with context variables passed to each. - Cache Panel: Shows cache hits, misses, and keys accessed during the request.
- Signals Panel: Displays all signals dispatched and the receivers triggered.
- Headers Panel: Inspects incoming client headers and outgoing response headers.
4. Enabling Debug Toolbar Inside Docker
When running Django inside Docker, request.META['REMOTE_ADDR'] is the Docker bridge IP (e.g. 172.18.0.1), which causes INTERNAL_IPS = ["127.0.0.1"] to fail. Use this callback to enable DDT inside Docker containers:
Practice Quiz
Deploying to Heroku
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Debugging Tips | Deploying to Heroku |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.