Using IPython Notebook with Django

Aug 30, 2012

IPython has a relatively new featured called the “Notebook,” which improves on the traditional terminal shell in many ways.

Notebook launches a web-based shell to an IPython session that has some very, very handy features, like the ability to save, edit and delete “notebooks” of code that are each comprised of organized cells of Python, text or Markdown. You can move the cells around, developing code interactively with documentation and notes to yourself, displaying anything that a browser could render: images, HTML, etc.

But! You can’t run a Django shell using notebook.

Use Django? Check out the book I’m writing: Supernatural Django ORM Performance. You might also like How Does Django’s StreamingHttpResponse Work, Exactly?.

With Django Extensions

The latest version of the Django Extensions app on Github has support for using the shell_plus command with Notebook. If you’re up to date, you should be able to use the following command to run a Django shell with Notebook:

$ ./ shell_plus --notebook

Without Django Extensions

If you’d rather not use the Django Extensions app, you can load an IPython extension that performs the imports that an IPython session needs to run Django.

I’ve packaged up such an extension (very simple) that you can install from by executing this command from within IPython:

This will download the module into ~/.ipython/extensions/ (The file merely attempts to load Django whenever you start IPython, unless an ImportError occurs.)

After installing the extension, add it to your IPython RC file. This is probably at ~/.ipython/profile_default/ If you don’t have one, you can use this command to create one with IPython (from the terminal shell, not within IPython):

$ ipython profile create

Then edit the created (or existing) file and add the following line somewhere after the line c = get_config():

(Or just append 'django_notebook' to the existing extensions list if it exists.)

Now you should be able to run ipython notebook from within a Django project and have access to all of the Django and project-related modules.