IPython, bpython and django

Tricks using ipython and bpython with django

Posted by @krazedkrish on September 10, 2015

IPython

I am sure you have used IPython for a number of purposes. For interactive shell, usually because it has some enhancements. You would also probable use it for RELP(Read Eval Print Loop). Let me brag about my favourite editor. RELP comes from the names of Lisp primitive function which implements this functionality, just the reason Emacs acts the way you want it to.

It's a must for a Pythonista to know this. Within any arbitary place in your python code (including django) you can drop into an IPython shell.

You didn't! Try inserting these, in between your codes.

from IPython import embed
embed()

Note: This will not work for older versions of python

By the way running python manage.py shell in django starts IPython by default if you have installed it.

bpython

You have used right! I am sure you loved its auto-complete and syntax highlight features. If you havent used it then, check out the screenshot below.

See more screenshots

Did you like it? If you did then you might want to use it for django as well.

Start by modifying your ~/.bashrc to define a python startup environment variable

export PYTHONSTARTUP=~/.pythonrc

Then insert the following code in ~/.pythonrc!

try:
    import os
    import sys
    project = os.path.basename( os.getcwd() )
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", project+".settings")
    exec("from %s import settings"%project)
    print('Imported django settings')
    try:
        exec_strs = ["from %s.models import *"%apps for apps in settings.INSTALLED_APPS ]
        for x in exec_strs:
            try:
                exec(x)
            except:
                pass
    except:
        pass
except:
    pass

Note: This will not work for older versions of python

Now run

$ exec $SHELL

From now, when you go to the django project folder(where manage.py resides) run bpython instead of python manage.py shell