vmonteco vmonteco - 4 months ago 224
Apache Configuration Question

Apache with virtualenv and mod_wsgi : ImportError : No module named 'django'

I'm trying to serve a little django project with the following Apache configuration :

Apache virtualhost configuration :

<VirtualHost *>
ServerName servername

[...]

<Directory "/path/to/project/project">
<Files wsgi.py>
Require all granted
</Files>
</Directory>

WSGIDaemonProcess project python-path=/path/to/project:/path/to/Envs/venv/lib/python3.5/site-packages
WSGIScriptAlias / /path/to/project/project/wsgi.py

</VirtualHost>


I also have the following wsgi.py :

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")
application = get_wsgi_application()


I have no problem to serve STATIC files and MEDIA files.

I also checked permissions and tried to recursively use 755, then 777 to my virtualenv's site-package directory. It didn't work.

But when trying to reach the root of my site I get the following :

from django.core.wsgi import get_wsgi_application
ImportError: No module named 'django'


I guessed that it was a Python path related problem since django is installed in my virtualenv. But I added the relevant python paths to the
WSGIDaemonProcess
's
python-path
attribute so I don't get why it doesn't work.

I also guess I could add the relevant directory to my Python path in my wsgi.py by using the
site
module
, but I'd like to understand why the Apache configuration I tried isn't enough. Did I miss something?

Answer

You are missing a WSGIProcessGroup directive or equivalent option on WSGIScriptAlias, so your application isn't actually being run in that daemon process group where you have set the virtual environment. See:

https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode

I would also recommend ensuring application group is set to '%{GLOBAL}' if that is the only application you are running in the daemon process group.

Thus use:

WSGIScriptAlias / /path/to/project/project/wsgi.py \
    process-group=project application-group=%{GLOBAL}

Also better to use python-home for the virtual environment.

    WSGIDaemonProcess project python-path=/path/to/project \
        python-home=/path/to/Envs/venv

See: