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

vmonteco picture vmonteco · Aug 4, 2016 · Viewed 22.3k times · Source

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

Graham Dumpleton picture Graham Dumpleton · Aug 4, 2016

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 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: