首页 > 解决方案 > Django+Apache | ImportError:没有名为 django 的模块

问题描述

我正在使用 Ubuntu OS 在 Linode 上托管我的 django 应用程序,并且我已经配置了 apache 网络服务器。当我尝试访问该站点时,我收到 500 Internal Server 错误 Apache 日志显示以下错误

Traceback (most recent call last):
File "/home/mosajan/artistry/artistry/wsgi.py", line 12, in <module>
from django.core.wsgi import get_wsgi_application<br>
ImportError: No module named 'django'
Target WSGI script '/home/mosajan/artistry/artistry/wsgi.py' cannot be loaded as Python module.

处理 WSGI 脚本“/home/mosajan/artistry/artistry/wsgi.py”时发生异常。

wsgi.py

import os
import sys
from django.core.wsgi import get_wsgi_application
sys.path.append('home/mosajan/artistry/')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'artistry.settings')
application = get_wsgi_application()

apache2 conf 文件 Artistry.conf

Alias /static /home/mosajan/artistry/static
<Directory /home/mosajan/artistry/static>
    Require all granted
</Directory>
<Directory /home/mosajan/artistry/artistry>
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>
WSGIScriptAlias / /home/mosajan/artistry/artistry/wsgi.py
WSGIDaemonProcess artistry python-path=/home/mosajan/artistry python-home=/home/mosajan/artistry/venv
WSGIProcessGroup artistry
WSGIPythonHome /home/mosajan/artistry/venv
WSGIPythonPath /hom/mosajan/artistry

文件结构
在此处输入图像描述

标签: pythondjangoapache

解决方案


此答案假设您手动激活了 venv,并且当您在项目文件夹中执行类似 python manage.py runserver 0.0.0.0:8000 之类的操作时,您是否能够看到项目并运行它而不会出现任何错误。如果是这种情况,这意味着您已经安装了 django 以及其他所需的项目需求/包,因此您现在可以停用 venv。

让我们首先确保将服务器的 IP 地址添加到 settings.py 文件中的 ALLOWED_HOSTS 中。

现在,在 venv 停用的情况下,确保安装 Apache 2.4 和带有模块 wsgi 的服务 httpd,这将帮助 Django 应用程序表现得像一个与 Apache 2.4 完全兼容的 Web 应用程序。如果你使用 yum 作为包管理器,那么你会运行这样的东西

yum install -y httpd python36u-mod_wsgi

现在让我们添加一个组 www

groupadd www

并编辑组

vim /etc/group

并在文件末尾添加

www:x:10000:root,apache

进入根目录并运行以下命令,使该目录的 www 组所有者

chown root.www -R /home/mosajan
chmod 775 -R /home/mosajan

现在,在您的 Apache 虚拟主机配置文件 Artistry.conf 中,您呈现的版本在最后一行 ( WSGIPythonPath /hom/mosajan/artistry) 中有错误。通过使用来修复它WSGIPythonPath /home/mosajan/artistry,保存文件并通过运行检查 Apache 配置文件是否正常

httpd -t

Syntax OK如果一切顺利,你应该得到。我假设您在一个<VirtualHost *:8000></VirtualHost>块中拥有该代码,并且还会向它添加一个 ErrorLog 并且可能会以不同的方式构造文件。检查它是否有效,如果没有,那么我会多考虑一下。您可以将此文档页面用作参考(如何将 Django 与 Apache 和 mod_wsgi 一起使用)。

然后,在您的 wsgi.py 文件中,我会将 sys.path.append 行更改为 have '/home/mosajan/artistry',因此您将拥有类似这样的内容

import os, sys
from django.core.wsgi import get_wsgi_application

sys.path.append('/home/mosajan/artistry')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'artistry.settings')
application = get_wsgi_application()

然后,打开 80 端口,启用并启动 httpd 并在浏览器中查看结果

enable httpd
systemctl start httpd
systemctl status httpd

您应该看到它开始正常,现在当您转到浏览器时,您应该能够看到项目运行良好。


推荐阅读