I'm using Python 3.9.9 for a Django 3 project. I would like to invoke my Python shell, via "python3 manage.py shell", so I have set these variables ...
$ echo $PYTHONSTARTUP
/home/myuser/cbapp/shell_startup.py
$ echo $PYTHONPATH/myuser
/home/myuser/cbapp/
My startup script is very simple ...
$ cat /home/myuser/cbapp/shell_startup.py
from cbapp.services import *
from cbapp.models import *
However, when I change to my project directory, activate my virtual environment, and attempt to invoke the shell, I get these errors complaining about not being able to find Django ...
$ cd /home/myuser/cbapp
$ ./venv/bin/activate
$ python3 manage.py shell
Traceback (most recent call last):
File "/home/myuser/cbapp/manage.py", line 10, in main
from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/myuser/cbapp/manage.py", line 21, in <module>
main()
File "/home/myuser/cbapp/manage.py", line 12, in main
raise ImportError(
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
However, Django has already been installed in my virtual environment ...
$ ls /home/myuser/cbapp/venv/lib/python3.9/site-packages/django/
apps conf core dispatch http __main__.py __pycache__ template test utils
bin contrib db forms __init__.py middleware shortcuts.py templatetags urls views
What else do I need to do to start my shell successfully?
./venv/bin/activate? That would execute a venv virtual environment in a subshell, not in your current shell.The documentation recommends:
And make sure your
PYTHONPATHinclude the directory where Django is installed. If Django is installed in the virtual environment, thenPYTHONPATHshould include the path to the site-packages directory of the virtual environment. However, it is typically not necessary to setPYTHONPATHif you have activated your virtual environment correctly.Once your virtual environment is activated, you should be able to run the Django shell using the following command from the root directory of your Django project (
/home/myuser/cbapp/in your case):Verify the Django installation within your virtual environment:
python3 -m django --version. If Django is installed correctly, this command will return the installed version of Django.Make sure the
DJANGO_SETTINGS_MODULEenvironment variable is set correctly. This variable should point to your settings file, usually in the formatmyproject.settings. You can set this variable in your shell or add it to yourshell_startup.pyfile with: