32đ
Just for completeness (but itâs 2018, so maybe things changed since this question was posted): you can actually install a Jupyter Python kernel in your Django environment that will then connect (run under) a different Jupyter server/environment (one where youâve installed widgets, extensions, changed the theme, etc.). django_extensions
right now still does only part of the required work đ
This assumes you have a Jupyter virtual environment thatâs separate from Djangoâs one and whose kernels/extensions are installed with --user
. All the Jupyter extensions (and their dependencies) are installed in this venv instead of the Djangoâs one/ones (youâll still need pandas, matplotlib, etc. in the Django environment if you need to use them together with Django code).
In your Django virtual environment (that can run a different version of Python, including a version 2 interpreter) install the ipython kernel:
pip install -U ipykernel
ipython kernel install --user --name='environment_name' --display-name='Your Project'
This will create a kernel configuration directory with the specified -âname in your userâs Jupyter kernel directory (on Linux it was ~/.jupyter/kernels
but in 2023 it became ~/.local/share/jupyter/kernels/
, while on OSX itâs ~/Library/Jupyter/kernels
) containing its kernel.json file and images/icons (by default the default Jupyter icon for the kernel weâre installing are used). This kernel will run inside the virtual environment what was active at creation, thus using the exact same version of python and all the installed modules used by our Django project.
Running ./manage.py shell_plus --notebook
does something very similar, but in addition to requiring everything (including the Jupyter server and all the extensions) installed in the current venv, itâs also unable to run notebooks in directories different from the projectâs root (the one containing ./manage.py
). In addition itâll run the kernel using the first executable called python it finds on the path, not the virtual environmentâs one, making it misbehave when not started from the command line inside an active Django virtual environment.
To fix these problems so that weâre able to create a Notebook running inside any Django project we have so configured and to be able to run notebooks stored anywhere on the filesystem, we need to:
- make sure the first âargvâ parameter contains the full path to the python interpreter contained in the virtual environment
- add (if not already present) an âenvâ section that will contain shell environment variables, then use these to tell Python where to find our project and which Django settings it should use. We do this by adding something like the following:
"env": {
"DJANGO_SETTINGS_MODULE": "my_project.settings",
"PYTHONPATH": "$PYTHONPATH:/home/projectuser/projectfolder/my_project"
}
- optional: change âdisplay_nameâ to be human friendly and replace the icons.
editing this environment kernel.json file youâll see something similar:
{
"display_name": "My Project",
"language": "python",
"env": {
"DJANGO_SETTINGS_MODULE": "my_project.settings",
"PYTHONPATH": "$PYTHONPATH:/home/projectuser/projectfolder/my_project"
},
"argv": [
"/home/projectuser/.pyenv/versions/2.7.15/envs/my_project_venv/bin/python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}",
"--ext",
"django_extensions.management.notebook_extension"
]
}
Notable lines:
-
"DJANGO_SETTINGS_MODULE": "my_project.settings": your settings, usually as seen inside your projectâs manage.py
-
"PYTHONPATH": "$PYTHONPATH:/home/projectuser/projectfolder/my_project": PYTHONPATH is extended to include your projectâs main directory (the one containing manage.py) so that settings can be found even if the kernel isnât run in that exact directory (here django_extensions will use a generic
python
, thus running the wrong virtual environment unless the whole Jupyter server is launched from inside it: adding this to the kernel.json created by django_extensions will enable it to run notebooks anywhere in the Django project directory) -
"/home/projectuser/.pyenv/versions/2.7.15/envs/my_project_venv/bin/python": first argument (argv list) of the kernel execution, should be the full path to your projectâs virtual environmentâs python interpreter (this is another thing django_extensions gets wrong: fixing this will allow any notebook server to run that specific Django environmentâs kernel with all its installed modules)
-
"django_extensions.management.notebook_extension": this is the extension that will load the âshell_plusâ functionality in the notebook (optional but useful đ )
77đ
-
Install
django-extensions
from https://github.com/django-extensions/django-extensions/blob/master/docs/index.rstpip install django-extensions
-
Change your settings file to include âdjango-extensionsâ
INSTALLED_APPS += ['django_extensions']
-
Run your Django server like this:
python manage.py shell_plus --notebook
-
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()
-
Now you should be able to import your django models etc. eg:
from app.models import Foobar Foobar.objects.all()
- [Django]-Django values_list vs values
- [Django]-Django â query filter on manytomany is empty
- [Django]-How to set environment variables in PyCharm?
25đ
Hereâs what just worked for me
- install Django Extensions (I used 1.9.6) as per other answers
- install jupyter
pip install jupyter
- some stuff I did to setup jupyter inside my Docker container â see below if this applies to you â
- from your base Django directory, create a directory for notebooks, e.g.
mkdir notebooks
- Go to that directory
cd notebooks
- start django extensions shell_plus from inside that directory:
../manage.py shell_plus --notebook
The notebook server should now be running, and may launch a new browser. If it doesnât launch a browser window, follow the instructions to paste a link or a token. - from the browser, open a new âDjango Shell Plusâ notebook, as per John Meeâs answerâs screenshot
AND, importantly, what didnât work was changing directories from inside the notebook environment. If I tried to work with any notebook that was not in the directory that manage.py shell_plus --notebook
was run in, then the kernal was not configured correctly. For me, having the notebook be configured for just a single directory at a time was good enough. If you need a more robust solution, you should be able set PYTHONPATH
prior to starting jupyter. For example add export PYTHONPATH="$PYTHONPATH:/path/to/django/project"
to a virtualenv activate script. But I havenât tried this.
â Docker Setup (optional)
- add a port mapping for your container for port 8888
For example, in your docker compose file;
ports:
- "8890:8888"
- Configure your project settings file to use ip 0.0.0.0
This is what I did:
NOTEBOOK_ARGUMENTS = [
'--ip', '0.0.0.0',
'--allow-root',
'--no-browser',
]
- [Django]-Django REST Framework â Separate permissions per methods
- [Django]-How to define two fields "unique" as couple
- [Django]-Django abstract models versus regular inheritance
17đ
Note: I am using Python 3.7 and Django 2.1, it works for Django 2.2. I donât have to run anything in my first cell, and this works like charm as long as you donât mind having the notebooks in the root of your Django project.
It is assumed that you have a virtual environment for your project, and it is activated. I use pipenv
to create virtual environments and track dependencies of my python projects, but it is up to you what tool you use.
It is also assumed that you have created a Django project and your current working directory is the root of this project.
Steps
-
Install
jupyter
Using pip
pip install jupyter
Using pipenv
pipenv install jupyter
-
Install
django-extentions
Using pip
pip install django-extensions
Using pipenv
pipenv install django-extensions
-
Set up
django-extensions
by adding it to theINSTALLED_APPS
setting of your Django projectsettings.py
file.:INSTALLED_APPS = ( ... 'django_extensions', )
-
Run the
shell_plus
management command that is part ofdjango-extensions
. Use the option--notebook
to start a notebook:python manage.py shell_plus --notebook
Jupyter Notebooks will open automatically in your browser.
-
Start a new Django Shell-Plus notebook
Thatâs it!
Again, you donât have to run anything in the first cell, and you can corroborate by running dir()
to see the names in the current local scope.
Edit:
If you want to put your notebooks in a directory called notebooks
at the root directory, you can do the following:
$ mkdir notebooks && cd notebooks
$ python ../manage.py shell_plus --notebook
Thanks to Mark Chackerian whose answer provided the idea to make run the notebooks in a directory other than the projectâs root.
These are the modules that are imported automatically thanks to shell_plus
:
# Shell Plus Model Imports
from django.contrib.admin.models import LogEntry
from django.contrib.auth.models import Group, Permission, User
from django.contrib.contenttypes.models import ContentType
from django.contrib.sessions.models import Session
# Shell Plus Django Imports
from django.core.cache import cache
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import transaction
from django.db.models import Avg, Case, Count, F, Max, Min, Prefetch, Q, Sum, When, Exists, OuterRef, Subquery
from django.utils import timezone
from django.urls import reverse
- [Django]-Sending an SMS to a Cellphone using Django
- [Django]-How do I use Django templates without the rest of Django?
- [Django]-(13: Permission denied) while connecting to upstream:[nginx]
10đ
Actually turns out you (might not) need to do all that crap. Just install django-extensions and run jupyter!
(myprojectvenv)$ cd myproject
(myprojectvenv)$ pip install jupyter
(myprojectvenv)$ pip install django-extensions
(myprojectvenv)$ jupyter notebook
In the browser, start a new âDjango Shell-Plusâ:
And you should be good to go. eg:
from myproject.models import Foobar
Foobar.objects.all()
- [Django]-What does error mean? : "Forbidden (Referer checking failed â no Referer.):"
- [Django]-How to execute a Python script from the Django shell?
- [Django]-How can I use Django permissions without defining a content type or model?
4đ
While the accepted answer from RobM works, it was less clear than it could be and has a few unnecessary steps. Simply put, to run notebooks through Django from a notebook environment outside of the project directory:
Install:
pip install django-extensions
Add 'django-extensions'
to your INSTALLED_APPS
list in settings.py
INSTALLED_APPS += ['django_extensions']
Run a notebook from within Django, then close it:
python manage.py shell_plus --notebook
This will create your kernel, which we will now edit to point to an absolute path of Python rather than a relative path.
On OSX, the kernel file is at: ~/Library/Jupyter/kernels/django_extensions/kernel.json
On Linux: ~/.jupyter/kernels/django_extensions/kernel.json
We only need to make two changes:
The first is to edit the first value in the "argv"
list from "python"
to the full address of the python version in your Django virtual environment. E.g.: "/Users/$USERNAME/Documents/PROJECT_FOLDER/venv/bin/python"
Secondly, to the "env"
dictionary, add "DJANGO_SETTINGS_MODULE": "mysite.settings",
where mysite
is the folder that contains your Django settings.
Optionally, change the value of "display_name"
.
Now when you run a notebook from any directory, choosing the "Django Shell-Plus"
kernel will allow your notebooks to interact with Django. Any packages such as pandas will need to be installed in the Django venv.
- [Django]-Django JSONField inside ArrayField
- [Django]-Get user profile in django
- [Django]-How do I use the built in password reset/change views with my own templates
3đ
The following does work for me using win10, Python 3.5, Django 1.10:
- Install Python with the Anaconda distribution so Jupyter will be installed as well
-
Install Django and install django-extensions:
pip install Django pip install django-extensions
-
Start a new Django project. You have to do that in that part of your tree of directories which can be accessed by Jupyter later.
django-admin startproject _myDjangoProject_
-
Start Jypter
- navigate Jupyter to the directory myDjangoProject and enter the first/top myDjangoProject-directory
- Start within the first/top myDjangoProject-directory a new Jupyter noteboke: new â> Django Shell-Plus
-
enter and run the following piece of code :
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myDjangoProject.settings") import django django.setup()
-
Note that this piece of code is the same as in manage.py, and note that âmyDjangoProject.settingsâ points to myDjangoProject/settings.py
-
Now you can start with examples, e.g.:
from django.template import Template, Context template = Template('The name of this project is {{ projectName }}') context = Context({'projectName': 'MyJypyterDjangoSite'}) template.render(context)
- [Django]-Django rest framework lookup_field through OneToOneField
- [Django]-How to force application version on AWS Elastic Beanstalk
- [Django]-OSError: [Errno 18] Invalid cross-device link
1đ
Run this command.
PYTHONPATH=/path/to/project/root DJANGO_SETTINGS_MODULE=settings python manage.py shell_plus --notebook
- [Django]-Alowing 'fuzzy' translations in django pages?
- [Django]-What is the Simplest Possible Payment Gateway to Implement? (using Django)
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
0đ
I will add some information to the very complete answer of RobM, for the benefit of the very rare developers that use buildout along with djangorecipe djangorecipe as I do⊠I refer to jupyter lab as I use that but I think all info can be applied to old jupyter notebooks.
When using buildout you end up with a âbin/djangoâ handler youâll use instead of âmanage.pyâ. Thatâs the script that defines the whole path. I added one more part in my buildout.cfg:
[ipython]
recipe = zc.recipe.egg
eggs = ${buildout:eggs}
extra-paths = ${buildout:directory}/apps
initialization = import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'web.settings'
so that another script named ipython
will be created in ./bin
directory. I point kernelspec to that interpreter. Moreover I use kernel
argument rather than "-m", "ipykernel_launcher"
so that the kernel definition I use is:
{
"argv": [
"/misc/src/hg/siti/trepalchi/bin/ipython",
"kernel",
"-f",
"{connection_file}",
"--ext",
"django_extensions.management.notebook_extension"
],
"display_name": "Trepalchi",
"language": "python"
}
Due to how the ipython script is created by buildout
thereâs no need to add environmental variables in my case.
As Rob already mentioned, jupiterlab is only installed in one environment where I start it with the command:
jupyter lab
not in the environment of Django project whare I only install ipykernel
(that has already a bunch of 20 dependencies).
Since I tend to have quite a lot of projects I find it usefull to have a single point where I start jupyter lab
with many links to the projects so that I can reach them easily. Thanks to the extension provided by django_extension I donât need any extra cell to initialize the notebook.
Any single kernel added in this way can be found with the command:
jupyter kernelspec list
And clearly listed in the launcher of jupyter lab
- [Django]-Profiling Django
- [Django]-Django error: got multiple values for keyword argument
- [Django]-How to implement followers/following in Django