How to do post-mortem debugging within Django's runserver?

348 Views Asked by At

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?

1

There are 1 best solutions below

0
LeoRochael On

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)