3

I am currently debugging a Django project which results in an exception. I would like to enter the ipdb post-mortem debugger. I've tried invoking ipdb as a script (cf. https://docs.python.org/3/library/pdb.html), but this just enters me to the first line of code:

> python -m ipdb manage.py runserver
> /Users/kurtpeek/myproject/manage.py(2)<module>()
      1 #!/usr/bin/env python
----> 2 import os
      3 import sys

ipdb> 

If I press c to continue, I just run into the error, with no possibility to drop into the debugger post-mortem. Presumably I could press n (next) until I get the error, but that would be quite cumbersome.

Is there a way to run python manage.py runserver with post-mortem debugging?

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526
  • 1
    Exceptions in Django are nearly all handled. So, they never reach the debugger. You should set a breakpoint on the `raise` line for the exception, or as close as possible to it on the stack. – Klaus D. Jul 26 '19 at 23:48

1 Answers1

0

If you know of a line that causes the exception, but don't know how "deep" inside it the exception is caused, you can get a post-mortem debugger for it by catching the exception and calling ipdb.post_mortem() in the exception handler.

For example, change your code from this:

def index(request):
    output = function_that_causes_some_exception()
    return HttpResponse(output)

To this:

def index(request):
    try:
        output = function_that_causes_some_exception()
    except:
        import ipdb
        ipdb.post_mortem()
        # Let the framework handle the exception as usual:
        raise
    return HttpResponse(output)

By the way, for server frameworks that could be spewing stuff in the console from other threads I highly recommend wdb, so that you can debug your django app from the comfort of a browser:

def index(request):
    try:
        output = function_that_causes_some_exception()
    except:
        import wdb
        wdb.post_mortem()
        # Let the framework handle the exception as usual:
        raise
    return HttpResponse(output)
LeoRochael
  • 14,191
  • 6
  • 32
  • 38