Looking for django Answers? Try Ask4KnowledgeBase
Looking for django Keywords? Try Ask4Keywords

Django Using Python Debugger (Pdb)


Most basic Django debugging tool is pdb, a part of Python standard library.

Init view script

Let's examine a simple views.py script:

from django.http import HttpResponse

def index(request):
    foo = 1
    bar = 0

    bug = foo/bar

    return HttpResponse("%d goes here." % bug)

Console command to run server:

python manage.py runserver

It's obvious that Django would throw a ZeroDivisionError when you try to load index page, but if we'll pretend that the bug is very deep in the code, it could get really nasty.

Setting a breakpoint

Fortunately, we can set a breakpoint to trace down that bug:

from django.http import HttpResponse

# Pdb import
import pdb

def index(request):
    foo = 1
    bar = 0
    # This is our new breakpoint
    bug = foo/bar
    return HttpResponse("%d goes here." % bug)

Console command to run server with pdb:

python -m pdb manage.py runserver

Now on page load breakpoint will trigger (Pdb) prompt in the shell, which will also hang your browser in pending state.

Debugging with pdb shell

It's time to debug that view by interacting with script via shell:

> ../views.py(12)index()
-> bug = foo/bar
# input 'foo/bar' expression to see division results:
(Pdb) foo/bar
*** ZeroDivisionError: division by zero
# input variables names to check their values:
(Pdb) foo
(Pdb) bar
# 'bar' is a source of the problem, so if we set it's value > 0...
(Pdb) bar = 1
(Pdb) foo/bar
# exception gone, ask pdb to continue execution by typing 'c':
(Pdb) c
[03/Aug/2016 10:50:45] "GET / HTTP/1.1" 200 111

In the last line we see that our view returned an OK response and executing as it should.

To stop pdb loop, just input q in a shell.