It's true packages exist to make it "easy" to use Django inside of a jupyter notebook. I seem to always run into issues successfully running these packages. I've found the below method useful although I cannot recall how I discovered how this works (aka attribution needed).
- Virtual Environment (
virtualenv,venv,pipenv, etc) - Django installed & project created (we'll use the project name
cfehome) - Jupyter installed at least in the virtual environment
It's simple. Just copy django_for_jupyter.py next to your Jupyter notebook files (.ipynb).
First cell
from django_for_jupyter import init_django
init_django("cfehome")Change
cfehometo your Django project name.
In, .env:
DJANGO_PROJECT="cfehome"
Or on the CLI:
DJANGO_PROJECT="cfehome" jupyter notebook
First cell
from django_for_jupyter import init_django
init_django()Change
cfehometo your Django project name.
Now that you've run init_django with no errors. You can import Django models:
Second Cell
from myapp.models import MyModel
MyModel.objects.all()Simple enough right?
Very cool and much appreciated!
I had issues getting this to work on my windows work pc. Not sure of the exact cause but I was having issues getting the correct directory with os.getenv('PWD').
Instead of:
PWD = os.getenv("PWD")I had to use:
PWD = os.path.dirname(os.getcwd())and then instead of os.getenv('PWD') on line 15, I used my new PWD variable:
sys.path.insert(0, PWD)