'Facing ModuleNotFoundError: No module named 'django' on Apache and Django Setup

Need help and clear understanding on Django and Apache based environment setup. My setup information as follows:

  • OS: Ubuntu 20.04
  • Apache2 configured with Virtual Host
  • Django2.2 installed without sudo
  • Python 3.8.10

Configuration from default-ssl.conf

 <IfModule mod_ssl.c>
    <VirtualHost *:443>
        WSGIScriptAlias /dynamic /var/project/module/wsgi.py
        WSGIApplicationGroup %{GLOBAL}
        ServerName localdev.test.com

        <Directory /var/www>
            AllowOverride None
            Require all granted
        </Directory>

        <Directory /var/project>
            AllowOverride None
            Require all granted
        </Directory>
    </VirtualHost>
</IfModule>

Now my issue is whenever I tried to access Django Admin component it throws following error in Apache error logs.

mod_wsgi (pid=12972): Failed to exec Python script file '/var/project/module/wsgi.py'.
mod_wsgi (pid=12972): Exception occurred processing WSGI script '/var/project/module/wsgi.py'.
Traceback (most recent call last):
File "/var/project/module/wsgi.py", line 16, in <module>
from django.core.wsgi import get_wsgi_application
ModuleNotFoundError: No module named 'django'

My setup does not use django virtual environment and also as mentioned above django is installed without sudo.

I tried to verify following information from my end.

pip list | grep -i django
It displays following list which includes django and related other modules required in the project:

Django                   2.2
django-contrib-comments  1.9.2
django-cors-headers      3.5.0
django-extensions        3.0.9
django-model-utils       3.1.2
django-mysql             3.9.0
django-ses               1.0.3
django-storages          1.6.3
django-user-agents       0.4.0

Also tried to verify path for Django:

>>> import sys
>>> sys.path
['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/ubuntu/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages']

Which includes django path: /home/ubuntu/.local/lib/python3.8/site-packages

Only solution works in this case is to install Django and other python modules with sudo, and I am not clear on why such behaviour. Also tried to check Django documentation and other forums and everywhere example used is for django virtual environment. Kind of curious what is the best way to run it without virtual environment.

Please help. Thank you in advance.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source