500 Internal Server Error - Django wsgi 错误显示在 apache2 日志中

500 Internal Server Error - Django wsgi error showing on apache2 log

我收到一个内部服务器错误并且不确定我是否需要更改 wsgi 中的某些内容。 该应用程序在端口 8000 上的虚拟环境中测试时运行良好。 我使用教程 https://www.youtube.com/watch?v=Sa_kQheCnds

遵循了所有步骤

apache 错误日志显示如下:

[Sun Feb 23 02:13:47.329729 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] mod_wsgi (pid=2544): Target WSGI script '/home/recprydjango/rec$
[Sun Feb 23 02:13:47.329817 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] mod_wsgi (pid=2544): Exception occurred processing WSGI script $
[Sun Feb 23 02:13:47.330088 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] Traceback (most recent call last):
[Sun Feb 23 02:13:47.330125 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870]   File "/home/recprydjango/recipe/app/wsgi.py", line 12, in <mo$
[Sun Feb 23 02:13:47.330130 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870]     from django.core.wsgi import get_wsgi_application
[Sun Feb 23 02:13:47.330148 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] ModuleNotFoundError: No module named 'django'

我有以下结构

(venv) recprydjango@recpry-django:~/recipe$ tree 
.
├── app
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── ...
│   │   └── wsgi.cpython-37.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
├── manage.py
├── media
│   └── images
│       ├── chocolatecake.png
│       └── ...
├── recipe
│   ├── admin.py
│   ├── apps.py
│   ├── forms.py
│   ├── __init__.py
│   ├── models.py
│   ├── __pycache__
│   │   ├── ...
│   │   └── views.cpython-37.pyc
│   ├── tests.py
│   └── views.py
├── requirements.txt
├── static
│   ├── admin
│   │   ├── css/...
│   │   ├── fonts/...
│   │   ├── img/...
│   │   └── js/...
│   └── smart-selects/...
├── templates
│   └── home.html
└── venv
    ├── bin
    │   ├── activate
    │   ├── activate.csh
    │   ├── activate.fish
    │   ├── easy_install
    │   ├── easy_install-3.6
    │   ├── pip
    │   ├── pip3
    │   ├── pip3.6
    │   ├── python -> python3
    │   └── python3 -> /usr/bin/python3
    ├── include
    ├── lib
    │   └── python3.6
    │       └── site-packages

settings.py

    import os
    import json

    with open('/etc/config.json') as config_file:
        config = json.load(config_file)

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = config['SECRET_KEY']

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = False

    ALLOWED_HOSTS = ['xx.xx.xx.xx']


    # Application definition

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        #--- ADDED APP recipe HERE !!!!
        'recipe',
        #--- ADDED Smart_Selects HERE !!
        'smart_selects',
        #Bootstap
        'crispy_forms',
'widget_tweaks',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'app.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        # --- TEMPLATE DIRECTORY
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
               'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'app.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

#--- ADDED THIS SECTION TO UPLOAD PHOTOS !!!! ---
MEDIA_ROOT =  os.path.join(BASE_DIR, 'media') 
MEDIA_URL = '/media/'
#------------------------------------------------

#--- ADDED THIS SECTION FOR SMART SELECTS !!! ---
USE_DJANGO_JQUERY = True
#------------------------------------------------

CRISPY_TEMPLATE_PACK = 'bootstrap4'

wsgi.py

"""
WSGI config for app 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/2.2/howto/deployment/wsgi/
"""

import os
import sys

sys.path.insert(0, '/home/recprydjango/recipe/')
sys.path.insert(0, '/home/recprydjango/recipe/app/')
sys.path.insert(0, '/home/recprydjango/recipe/recipe/')

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')

application = get_wsgi_application()

apache 配置文件

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com

        ServerAdmin webmaster@localhost
        DocumentRoot /var/www/html

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf

        Alias /static /home/recprydjango/recipe/static
        <Directory /home/recprydjango/recipe/static>
        Require all granted
        </Directory>

        Alias /media /home/recprydjango/recipe/media
        <Directory /home/recprydjango/recipe/media>
        Require all granted
        </Directory>

        <Directory /home/recprydjango/recipe/app>
        <Files wsgi.py>
        Require all granted
        </Files>
        </Directory>

        WSGIScriptAlias / /home/recprydjango/recipe/app/wsgi.py
        WSGIDaemonProcess django_app python-path=/home/recprydjango/recipe python-home=/home/recprydjango/recipe/venv
        WSGIProcessGroup django_app



</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

你的文件夹结构我有点不清楚,最好不要把屏幕截图放在那里,而是使用 find .tree (linux) 命令命令行向我们发送一个干净的结构。对我来说 'app' 和 'recipe 在同一级别,那么 'app' 是您的项目文件夹吗?通常 django 已经创建了一个像

这样的文件夹结构
/app/app/
/app/manage.py

您的 venv 文件夹包含 python 文件等,并且位于 djangoproject 中,对吗?这也有点奇怪。

所以对我来说,你似乎重命名了一些你不应该重命名的东西,因此你的项目文件夹有点难以处理。

可以看到wsgi脚本是运行,但显然是找不到django路径。我认为原因是因为你的虚拟环境是放在 django 项目里面的。这没什么大不了的,我认为您可以通过以下方式将 django-project-folder 添加到 .wsgi 文件来修复它:

sys.path.insert(0, '/path/to/your/django/project/')

不过,我建议您在下一个 Django 项目中将虚拟环境放在 Django 创建的文件夹之外。我希望至少现在您可以继续之前提到的小修改。与 Django 一起玩得开心!

我 运行 在两个不同的 python 版本本地 3.7 和服务器 3.6