How to set up Jupyter/IPython Notebook for Django

djangoipythonjupyterjupyter-notebook

I have been using the method described in this post for setting up IPython Notebook to play nicely with Django. The gist of the method is to create an IPython extension which sets the DJANGO_SETTINGS_MODULE and runs django.setup() when IPython starts.

The code for the extension is:

def load_ipython_extension(ipython):
    # The `ipython` argument is the currently active `InteractiveShell`
    # instance, which can be used in any way. This allows you to register
    # new magics or aliases, for example.
    try:
        import os
        os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
        import django
        django.setup()
    except ImportError:
        pass

With a recent upgrade to Jupyter Notebook this setup is now broken for me. I am able to run Django code in the Jupyter notebook by adding a similar bit of code to the first cell of the notebook. However, I was not able to figure out how to get Jupyter to run the extension automatically so I would not have to do this again for each and every notebook I am creating.

What should I do to get Django and Jupyter to play nicely?

UPDATE:
For @DarkLight – I am using Django 1.8.5 with Jupyter 1.0.0. The code I run in the notebook is:

import os, sys
sys.path.insert(0, '/path/to/project')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settingsfile")
import django
django.setup()

Best Answer

  1. Install django-extensions from https://github.com/django-extensions/django-extensions/blob/master/docs/index.rst

     pip install django-extensions
    
  2. Change your settings file to include 'django-extensions'

     INSTALLED_APPS += ['django_extensions']
    
  3. Run your Django server like this:

    python manage.py shell_plus --notebook
    
  4. alter to suit, and run this in your first cell

    import os, sys
    PWD = os.getenv('PWD')
    os.chdir(PWD)
    sys.path.insert(0, os.getenv('PWD'))
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "local_settings.py")
    import django
    django.setup()
    
  5. Now you should be able to import your django models etc. eg:

    from app.models import Foobar
    Foobar.objects.all()