Use BPython as debugger for a Django application

436 views Asked by At

I'm currently developping a Django application and I like using the pdb to know in which state is my application and some stuff like that. I would like to have all the amazing capabilites of BPython inside the debuger... Like autocompletion and things like that.
Is that even possible ? Thanks :)

2

There are 2 answers

0
Nick Sweeting On

Put some code in your python repl startup file to detect you're in a Django project, and perform the necessary imports:

  1. put this in your ~/.bashrc or ~/.bash_profile
    export PYTHONSTARTUP=~/.pythonrc

  2. Create or edit your ~/.pythonrc:

    try:
        from django.core.management import setup_environ
        import settings
        setup_environ(settings)
        print 'imported django settings'
    except:
        pass
    

    OR Use this more involved snippet that imports all your django modules and works in project subdirectories here: https://gist.github.com/pirate/2659b242bded82c3c58f2458e6885738#file-pythonrc-L56

0
gtalarico On

I know this is quite old but I still couldn't find a solution I liked, and ended up with the solution below which uses a django command.

The other answer by Nick works as well too, but I don't like having to add Django specific things in my global .pythonrc

#myapp/management/commands/bshell.py

from django.core.management.base import BaseCommand
from django.apps import apps


class Command(BaseCommand):
    help = "Runs the bpython interactive interpreter if it's installed."
    requires_model_validation = False

    def handle(self, *args, **options):
        loaded_models = apps.get_models()

        models = {}
        for model in loaded_models:
            models[model.__name__] = model

        import bpython

        bpython.embed(models)
.venv ❯ python manage.py bshell
>>> Locat
┌───────────────────────────────────────────────────────────────────────────────────┐
│ Location(                                                                         │
└───────────────────────────────────────────────────────────────────────────────────┘