How to debug Django using the Python Debugger PDB

Mar 15, 2011

Avatar of Olivier Girardot
Olivier Girardot

Even if that seems common sense, i found out that there's not that much sources that explains how to use PDB with Django's bundle webserver. So here we go, let's say you have some treatment like that :


text
def search(request):
    """
        search (it's written up there).
    """
    if request.method == 'POST':
        item = request.POST['item']
        # separate numeric part from string part and
        # add a % in case no numeric value is provided
        (num, test) = re.match("([d]*)([D]*)", item).groups()
        if not num:
            num = "%"
                .... # query in database

Now what we want to check, is that the "not num" part is doing its job in replacing any non-numeric part by a wildcard. so we'll add this statement "import pdb; pdb.set_trace()" to set up a breakpoint that PDB will be able to use :

text
def search(request):
    """
        ase.
    """
    if request.method == 'POST':
        item = request.POST['item']
        # separate numeric part from string part and
        # add a % in case no numeric value is provided
        (num, test) = re.match("([d]*)([D]*)", item).groups()
                # the breakpoint will be here :
                import pdb; pdb.set_trace()
        if not num:
            num = "%"
                .... # query in database

And then, all we need to do is run the standalone embedded web server of Django using pdb. At first PDB (just like GDB) will wait for you to use the command c (continue) to launch the program and will only stop when he reaches a breakpoint :

text
 python -m pdb manage.py runserver

Eventually when you'll reach the breakpoint, you can use the commands locals(), globals() to see all the variables you can access. For more on how to use PDB and debugging in Django i refer you to the nice tutorial by Mike Tigas. Vale

Menu

Follow

Copyright © 2026
 Olivier Girardot's Ramblings
  Powered by   Writizzy