Search code examples
pythondjangowsgi

Django ModuleNotFoundError: No module named 'myProject'


ModuleNotFoundError: No module named 'myProject' error, but I do not know the cause. I am glad if you tell me.

・ CentOS 7.2
・ Python 3.6
・ Django 2.0
・ apache 2.4

I set the virtual environment as follows

pip install virtualenv
mkdir xxx
cd xxx 
python3 -m venv xxx
source xxx/bin/activate
pip install mod_wsgi
mod_wsgi-express module-config
LoadModule wsgi_module "/home/username/myProject/myProject/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so"
WSGIPythonHome "/home/username/myProject/myProject"

■ /etc/httpd/conf.d/django.conf

NameVirtualHost *:80
LoadModule wsgi_module /home/username/myProject/myProject/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
WSGIPythonHome /home/username/myProject/myProject
WSGISocketPrefix /var/run/wsgi
<VirtualHost *:80>

  ServerName xxx.com
  DocumentRoot /home/username

  WSGIApplicationGroup %{GLOBAL}
  WSGIDaemonProcess xxx python-home=/home/username/myProject/myProject python-path=/home/username/myProject/myProject/lib/python3.6/site-packages
  WSGIProcessGroup xxx
  WSGIScriptAlias / /home/username/myProject/myProject/wsgi.py

  <Directory /home/username/myProject/myProject/static>
      Require all granted
  </Directory>

  <Directory /home/username/myProject/myProject>
      <Files wsgi.py>
          Require all granted
      </Files>
  </Directory>
</VirtualHost>

■ wsgi.py

import os,sys

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxx.settings")

application = get_wsgi_application()

Solution

  • Read:

    The WSGIPythonHome directive or python-home option should point at the root directory for the Python virtual environment. This should be the same value as sys.prefix has when Python is run for that virtual environment.

    The WSGIPythonPath directive or python-path option would then be set to your project code directory in which modules/packages exist, likely /home/username/myProject in your case.

    Do not use these later options to point at the site-packages directory, use the first options for specifying the location of the virtual environment.

    I would suggest since you are using daemon mode to add:

    WSGIRestrictEmbedded On
    

    after the LoadModule line. Then remove the WSGIPythonHome and WSGIPythonPath and rely on python-home and python-path options on WSGIDaemonProcess instead.

    BTW, DJANGO_SETTINGS_MODULE wouldn't be xxx.settings. You likely mean myProject.settings.

    Also, it appears that you have your virtual environment being your project code directory. If that is the case, is not really recommended. Create the virtual environment as a distinct sub directory somewhere of its own. Don't intermingle it with your code as then it becomes really hard to remove the virtual environment and re-create it.