Is there a guide for using Django in a Jupyter notebook in 2022?

Hi there,

I’m a fan of django, and I’m a fan of using Jupyter notebook to build narratives and tutorials of doing some quick and dirty analysis in them as an alternative to doing the same in shell sessions which are harder for me to share.

Normally these are fairly short, and they use the models and modules exposed by django, where in the notebook they are available along the same paths I might use in the app.

So for example, if I wanted to do some analysis on the Foo model like this in the shell:

from apps.my_app.models import FooModel

results = []

for my_instance in FooModel.object.all():

I would instead do the same in a notebook cell. The main difference being that I’d typically have results as the last line in the notebook cell, because I can then see the result, rendered, like in a REPL.

This is nice because I have all of HTML and markdown available to me for presenting results, and where I can make html or PDF exports of my session for easier sharing to less techy people.

I might begin by running this command (assuming I have django_extensions installed which gives me the nifty django kernel that jupyter recognises, and connect to, when I run this in my project root:

jupyter lab

Which opens a screen where I can then choose to open a .ipynb analysis file, which is connected to a django shell session, using the same settings as have been defined in my DJANGO_SETTINGS_MODULE.

This lets me do analysis like this screenshot suggests:

The screenshot above is a sample from some analysis of a local staging snapshot of a database I’m working with, for example, but you can connect to anything you settings file lets to connect to like a real live database if you were feeling appropriately YOLO.

This is all handy, and works for analysis in my project root, I’d prefer to put my analysis notebooks in another place, like a folder kept out of the project source control like analysis.

This would allow me to keep that in source control in a private repo, tha is separate from a main codebase repo. I was working on an open source project, I might not want to check the notebooks into the main repo, as the content might not be suitable for the public repo, for all kinds of reasons.

Anyway, given how popular django is, and how popular jupyter is, I figured there would be some recent best practice written up.

Have you folks found any recent links?

I put together this talk about the subject a few years back, but I’d really appreciate seeing work by others as I can’t be the only person to find the combination of django’s ease of use, and jupyters power for building nice narratives and demos compelling.

The link to the deck I presented seems to be dead now, but if you’re curious, you can still see it at the link below: