How to run Jupyter shells for Django app

To Nha Notes | Sept. 9, 2021, 2:02 p.m.

We can test code in jupyter environment inside recent version of visual code. Select jupyter kernel and choose a target virtual environment of Django app to activate.

Installation:

pip install python-dotenv

Add below code to begin of Jupyter shell to activate app environment.

import os
import sys
from dotenv import load_dotenv

sys.path.append("/path/to/project_folder")
os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<project_name>.settings")
load_dotenv(dotenv_path="/path/to/project_folder/env.env")

Now we can start adding shells to execute test code.

from <project_name>.models import MyModel
MyModel.objects.filter(...)
...