Skip to content

Instantly share code, notes, and snippets.

@EtsuNDmA
Last active April 29, 2024 04:42
Show Gist options
  • Star 23 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EtsuNDmA/dd8949061783bf593706559374c8f635 to your computer and use it in GitHub Desktop.
Save EtsuNDmA/dd8949061783bf593706559374c8f635 to your computer and use it in GitHub Desktop.
Two ways to integrate Django with Jupyter (JupyterLab)

⚠️ This gist was the first time written in 2018. It was tested with django==2.2.x. It's likely to be relevant for the newer versions of django and jupyter, but I did't check that.

2023-03-15: checked it for python == 3.11, django == 4.1.7, jupyterlab = 3.6.1, django-extensions == 3.2.1, jupyter-server <= 2.0.0

Django_jupyter

Using Django project in Jupyter or JupyterLab

Method 1 (using shell_plus)

We assume that django and jupyter are already installed

  1. Install django-extensions

    pip install django-extensions
  2. Add django-extensions app into Django settings

    INSTALLED_APPS += ['django_extensions']
  3. Add jupyter setting into Django settings

    NOTEBOOK_ARGUMENTS = [
        '--ip', '0.0.0.0',
        '--port', '8888',
    ]
    IPYTHON_KERNEL_DISPLAY_NAME = 'Django Kernel'

    All params you can find in jupyter help

    jupyter --help-all
  4. Install JupyterLab (optional). To start JupyterLab by default add this to Django settings

    try:
        import jupyterlab
        NOTEBOOK_DEFAULT_URL = '/lab'  # Using JupyterLab
    except ImportError:
        NOTEBOOK_DEFAULT_URL = '/tree'  # Using Jupyter
    
    NOTEBOOK_DIR = BASE_DIR / "notebooks"
    
    NOTEBOOK_ARGUMENTS = [
        '--ip', '0.0.0.0',
        '--port', '8888',
        '--notebook-dir', NOTEBOOK_DIR,
        '--NotebookApp.default_url', NOTEBOOK_DEFAULT_URL,
    ]
    IPYTHON_KERNEL_DISPLAY_NAME = 'Django Kernel'
    
    # if you want to use Chrome by default
    # os.environ.setdefault('BROWSER', 'google-chrome')
  5. Run jupyter

    PYTHONPATH=$(pwd):$PYTHONPATH python manage.py shell_plus --notebook

    for notebook>=7.0.0 (django-extensions/django-extensions#1835)

    PYTHONPATH=$(pwd):$PYTHONPATH python manage.py shell_plus --lab

    Browser will be opened at http://[ip]:[port]/tree

  6. Create new notebook using Django Kernel

    We can see that all Django models are already imported

    locals()

    WARNING Model names collisions will be resolved by (collision resolver)

  7. Be careful with async. Read https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#difference-between-terminal-ipython-and-ipykernel and https://docs.djangoproject.com/en/4.1/topics/async/#async-safety

    TL;DR

    os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

Method 2

In this case you don't need to install django-extensions. However it is less convenient

Initialize Django in the first cell of each notebook

import os, sys
import django
PROJECTPATH = '/my/django/project/path'
sys.path.insert(0, PROJECTPATH)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my.django.settings.module")
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"  # https://docs.djangoproject.com/en/4.1/topics/async/#async-safety
os.chdir(PROJECTPATH)
django.setup()

Than you can import models

from myapp.models import Vehicle
Vehicle.objects.count()
@EtsuNDmA
Copy link
Author

EtsuNDmA commented Apr 4, 2024

@azegas thanks, I updated the gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment