【问题标题】:When I tried running my python program, I encountered a Django importing module Error当我尝试运行我的 python 程序时,我遇到了一个 Django 导入模块错误
【发布时间】:2019-04-29 20:50:03
【问题描述】:

当我尝试在本地机器上运行 python 程序时,我遇到了这个错误:

Traceback (most recent call last):
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run
    handler = self.get_handler(*args, **options)
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler
    handler = super().get_handler(*args, **options)
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler
    return get_internal_wsgi_application()
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 50, in get_internal_wsgi_application
    ) from err
django.core.exceptions.ImproperlyConfigured: WSGI application 'mysite.wsgi.application' could not be loaded; Error importing module.

网上也有类似的帖子,我尝试了每个帖子中建议的解决方案,但没有一个可以解决我的错误。

这是我的setting.py的内容

我的 python 版本:Python 3.7.3 我的 Django 版本:2.2

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 2.0.7.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os
import django_heroku 
import dj_database_url

config = dj_database_url.config

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


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

# SECURITY WARNING: keep the secret key used in production secret!
DEBUG = False

# Experimenting here
ALLOWED_HOSTS = ["localhost", "https://stormy-stream-43261.herokuapp.com/"]

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    '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 = 'mysite.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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 = 'mysite.wsgi.application'

# WSGI_APPLICATION = 'mysite.wsgi.application'
# from django.core.exceptions import ImproperlyConfigured

# def get_env_variable(var_name):
#     try:
#         return os.environ[var_name]
#     except KeyError:
#         error_msg = "Set the %s environment variable" % var_name
#         raise ImproperlyConfigured(error_msg)

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

# one for development (maybe move that to local postgres) and another for running and development
DATABASES = {

    # 'default': {
    #    'ENGINE': 'django.db.backends.postgresql',
    #    'NAME': 'xsboediz',
    #    'USER': 'xsboediz',
    #    'PASSWORD': '****************',
    #    'HOST': 'baasu.db.elephantsql.com',
    #    'PORT': '5432'
    # }

    #
    # 'default': dj_database_url.config(
    #     default=config('DATABASE_URL')
    # )
    #

    'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'mydatabase',
        }


}



# Password validation
# https://docs.djangoproject.com/en/2.0/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.0/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.0/howto/static-files/

#STATIC_URL = './blog/staticfiles/'
STATIC_URL = '/static/'

# STATICFILES_DIRS = (
#     #'/Diversity_Policy_Site/blog/static',
#     os.path.join(BASE_DIR, '/static/'),
# )
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

django_heroku.settings(locals())

我之前发布过类似的帖子,但没有人再查看该帖子,所以我在这里创建了另一个帖子,看看是否有人可以提供帮助。任何帮助或建议表示赞赏。

【问题讨论】:

  • 看起来您正在使用 Heroku 进行托管。您是否在此处遵循 Heroku 的快速入门:devcenter.heroku.com/articles/django-app-configuration?如果是这样,在您添加任何自己的代码之前,它是否有效?
  • 你的 wsgi.py 文件是什么样的?
  • @robert lee 这是 wsgi.py 的内容: """ mysite 项目的 WSGI 配置。它将 WSGI 可调用对象公开为名为 application 的模块级变量。有关更多信息这个文件,见docs.djangoproject.com/en/2.0/howto/deployment/wsgi """ import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() application = DjangoWhiteNoise (应用)
  • @Robert H 我刚刚试过那个网页,它没有用,它仍然显示同样的错误
  • @robert lee 注释掉那行代码后,程序还是报同样的错误,我用同样的命令运行程序。

标签: python django python-3.x


【解决方案1】:

好的,我终于在网上找到了解决方案: 第一步:pip卸载whitenoise 然后执行: pip install "whitenoise

另外,感谢所有在这篇文章中提出建议的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2021-04-26
    • 2021-05-04
    • 2020-12-12
    • 2020-11-29
    相关资源
    最近更新 更多