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
Using Django project in Jupyter or JupyterLab
We assume that django and jupyter are already installed
-
Install django-extensions
pip install django-extensions
-
Add django-extensions app into Django settings
INSTALLED_APPS += ['django_extensions']
-
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
-
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')
-
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
-
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)
-
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"
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()
@x0lani @EtsuNDmA thanks for sharing this solution.
Method 2 works for me.
Method 1 returns this:
I am using django 4.2 abd python 3.10.
I am using Windows WSL (Linux subsystem on a windows machine)
Jupyter notebook is installed. not sure why method 1 is failing in my case.
This works:
But not this: