django.core.exceptions.AppRegistryNotReady:应用程序尚未加载。(django 2.0.1)(Python 3.6)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48163641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:34:33  来源:igfitidea点击:

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. (django 2.0.1)(Python 3.6)

pythondjangopython-3.xpythonanywheredjango-2.0

提问by Limerin555

It's my first time trying to deploy a Django app(django 2.0.1)(Python 3.6) to pythonanywhere, it is a simple portfolio app with no models, no bootstrap. Just Django, HTML, CSS & Javascript.

这是我第一次尝试将 Django 应用程序(django 2.0.1)(Python 3.6)部署到 pythonanywhere,它是一个简单的投资组合应用程序,没有模型,没有引导程序。只是 Django、HTML、CSS 和 Javascript。

After pulling it from the Github repo onto pythnanywhere with their bash console, I run :

使用 bash 控制台将其从 Github 存储库拉到 pythnanywhere 后,我运行:

python manage.py migrate

& was hit with this error :

& 遇到了这个错误:

Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-
packages/django/core/management/__init__.py", line 371, in 
execute_from_command_line
utility.execute()
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-
packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-
packages/django/core/management/__init__.py", line 216, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-
packages/django/core/management/__init__.py", line 36, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-
packages/django/core/management/commands/migrate.py", line 12, in <module>
from django.db.migrations.autodetector import MigrationAutodetector
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-
packages/django/db/migrations/autodetector.py", line 11, in <module>
from django.db.migrations.questioner import MigrationQuestioner
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-
packages/django/db/migrations/questioner.py", line 9, in <module>
from .loader import MigrationLoader
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 8, in <module>
from django.db.migrations.recorder import MigrationRecorder
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 9, in <module>
class MigrationRecorder:
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 22, in MigrationRecorder
class Migration(models.Model):
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__
app_config = apps.get_containing_app_config(module)
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config
self.check_apps_ready()
File "/home/Limerin555/.virtualenvs/projectenv/lib/python3.6/site-packages/django/apps/registry.py", line 127, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I tired looking for solutions everywhere I could possibly find but nothing really helps, I've even tried adding this line to my settings.py :

我厌倦了在任何可能找到的地方寻找解决方案,但没有任何帮助,我什至尝试将此行添加到我的 settings.py :

import django
django.setup()

underneath this line :

在这条线下面:

SECRET_KEY = os.environ.get("SECRET_KEY")

as suggested from this post, but to no avail.

按照this post的建议,但无济于事。

Here is my settings.py :

这是我的 settings.py :

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATIC_DIR = os.path.join(BASE_DIR, "static")

SECRET_KEY = os.environ.get('SECRET_KEY')

import django
django.setup()

DEBUG = False

ALLOWED_HOSTS = ["limerin555.pythonanywhere.com"]

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

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.clickHymaning.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'limerin.urls'

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


DATABASE_PATH = os.path.join(BASE_DIR, 'db.sqlite3')

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': DATABASE_PATH,
    }
}


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',
    },
]

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Singapore'

USE_I18N = True

USE_L10N = True

USE_TZ = True


STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]

I am really lost on this, hoping someone can help shed some light on what's the real problem here.

我真的很迷茫,希望有人能帮助阐明这里的真正问题。

回答by Janusz Skonieczny

Please run checkdjango-admin commandto see if it have detected any errors.

请运行checkdjango-admin 命令以查看它是否检测到任何错误。

python manage.py check

and/or

和/或

django-admin check

回答by Alexey Trofimov

Overcame similar situation just now.

刚刚克服了类似的情况。

All you really need is this:

你真正需要的是:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")

And then these lines:

然后这些行:

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

After that you can easily import models without AppRegistryNotReady: Apps aren't loaded yet.

之后,您可以轻松导入模型,而无需 AppRegistryNotReady: Apps aren't loaded yet.

UPDATE: This is really exactly the 4 code lines from wsgi.py file in your project's folder.

更新:这确实是项目文件夹中 wsgi.py 文件中的 4 行代码。

FOR DJANGO 3.0In Django 3+ an extra variable is needed to resolve sync/async confusing:

FOR DJANGO 3.0在 Django 3+ 中,需要一个额外的变量来解决同步/异步混淆:

os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"

回答by Glenn

The Django docs say that django.setup loads the settings from settings.py as its first act, so it seems like a bad idea to run that in settings.py.

Django 文档说 django.setup 从 settings.py 加载设置作为它的第一个动作,所以在 settings.py 中运行它似乎是一个坏主意。

Try commenting out apps in INSTALLED_APPS one at a time - you'll probably find that one of them is not loading for some reason. Once you know which one it is, you can work out what is wrong with it.

尝试一次在 INSTALLED_APPS 中注释掉一个应用程序 - 您可能会发现其中一个由于某种原因没有加载。一旦你知道它是哪一个,你就可以弄清楚它有什么问题。

回答by Olivier Pons

My problem was that I was trying to import before the setup was ran. Here's my solution: make the import afterthe setup:

我的问题是我在运行安装程序之前尝试导入。这是我的解决方案:在设置进行导入:

import django

# some variable declarations    
world_mapping = {
    'osm_id': 'osm_id',
}    

if __name__ == '__main__':
    django.setup()
    # import AFTER setup
    from app.models import WorldBorder
    # from now I can access WorldBorder!!

回答by Rohit Sehgal

There could be several reasons for this error but all of them are related to project/settings.pyfile.

此错误可能有多种原因,但所有原因都与project/settings.py文件有关。

  1. Check if you have initialised SECRET_KEYin it.
  2. Check if you have application in INSTALLED_APPSand is not installed.
  1. 检查您是否已SECRET_KEY在其中初始化。
  2. 检查您是否有应用程序INSTALLED_APPS并且未安装。

回答by Little Brain

It took me a while to understand that every time you run manage.py somecommand, you need to provide the same settings / environment variables that you need when you run ./manage.py runserver.

我花了一段时间才明白,每次运行时manage.py somecommand,您都需要提供运行时所需的相同设置/环境变量./manage.py runserver

For example I load SECRET_KEY in from an environment variable in a file called .env. So I need to do this in order to make and run migrations:

例如,我从名为.env. 所以我需要这样做才能进行和运行迁移:

. .env
./manage.py makemigrations --settings=djangoproject.settings.development
./manage.py migrate --settings=djangoproject.settings.development

回答by yattara

First at all: check if you have the same code like below in yourproject.wsgi.py

首先:检查您的project.wsgi.py中是否有与下面相同的代码

"""
WSGI config for store 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.0/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "store.settings")

application = get_wsgi_application()

Like mentioned this config is for django2.0, seek to have the rigth code for your version.

就像提到的这个配置是针对 django2.0 的,寻求你的版本的正确代码。

THENType this below code in your ~/.basrc or ~/.zshrc for zsh, anyway type this code in your rigth shell file.

然后在您的 ~/.basrc 或 ~/.zshrc 中为 zsh 键入以下代码,无论如何在您的 rigth shell 文件中键入此代码。

export SECRET_KEY="type_a_long_random_char_printable_here"
#like this: export SECRET_KEY="hjfhskjh(@/;,?jhod=sjhGJKghgjGHJh#=}"

happened me for django deployment on heroku , after over checked, checked again your SECRET_KEY="remove here all char like those: $\` "and you hav'nt specified any directory that does'nt exist.

我在 heroku 上部署了 django,经过检查,再次检查你的SECRET_KEY="remove here all char like those: $\` "并且你没有指定任何不存在的目录。