Ubuntu22.04下Django+Apache+mod_wsgi部署遇ModuleNotFoundError求助
解决Django+Apache+mod_wsgi部署的ModuleNotFoundError问题
问题分析
你的场景中,runserver能正常运行、纯WSGI的Hello World也能正常响应,但Django应用报ModuleNotFoundError: No module named 'mytest',核心原因是Python的sys.path未包含Django项目根目录,导致无法找到包含settings的mytest子模块。
具体修复步骤
1. 修改wsgi.py,添加项目根目录到Python路径
在wsgi.py中,激活虚拟环境之后、导入Django相关代码之前,添加项目根目录到sys.path:
import sys # 将项目根目录添加到Python搜索路径 sys.path.append('/home/user/myprojects/mytest')
修改后的完整wsgi.py示例:
""" WSGI config for mytest project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ """ python_home='/home/user/.virtualenvs/myproject' activate_this= python_home + '/bin/activate_this.py' with open(activate_this)as f: code=compile(f.read(),activate_this,'exec') exec(code, dict(__file__=activate_this)) import os import sys # 添加项目根目录到Python路径 sys.path.append('/home/user/myprojects/mytest') from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mytest.settings') application = get_wsgi_application()
2. 优化Apache配置(规范虚拟环境管理)
手动激活虚拟环境容易引发路径冲突,建议直接在Apache配置中指定虚拟环境路径,同时补充项目根目录的访问权限:
WSGIDaemonProcess mytest python-home=/home/user/.virtualenvs/myproject WSGIProcessGroup mytest WSGIScriptAlias /mytest /home/user/myprojects/mytest/mytest/wsgi.py # 允许Apache访问项目根目录 <Directory /home/user/myprojects/mytest> Require all granted </Directory> # 允许Apache访问wsgi.py所在的子目录 <Directory /home/user/myprojects/mytest/mytest> Require all granted </Directory>
修改后可删除wsgi.py中手动激活虚拟环境的代码,让mod_wsgi自动管理虚拟环境,减少出错概率。
3. 确保文件权限正确
Apache以www-data用户运行,必须拥有项目目录和文件的读取权限:
# 设置目录所属用户组为www-data sudo chown -R user:www-data /home/user/myprojects/mytest # 设置目录和文件的读写执行权限 sudo chmod -R 755 /home/user/myprojects/mytest
验证修复
完成以上修改后,重启Apache服务:
sudo systemctl restart apache2
再次访问http://你的服务器IP/mytest,即可正常显示Django的默认成功页面。
内容的提问来源于stack exchange,提问作者henkwitte
相关产品推荐
相关产品推荐

