提升AppRegistryNotReady(“尚未加载应用程序。”)django.core.exceptions.AppRegistryNotReady:尚未加载应用程序..如何加载应用程序?

时间:2018-02-02 09:09:06

标签: python django

enter image description here我试图运行以下命令::

python populate_book.py

并坚持这个错误::

raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

整个回溯如下::

Traceback (most recent call last):
  File "populate_book.py", line 6, in <module>
    from opac.models import Book, BookCopy
  File "/home/prashant/Desktop/po/opac/models.py", line 6, in <module>
    from transactions.models import EndUser
  File "/home/prashant/Desktop/po/transactions/models.py", line 4, in <module>
    class EndUser(models.Model):
  File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/db/models/base.py", line 110, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/apps/registry.py", line 247, in get_containing_app_config
    self.check_apps_ready()
  File "/home/prashant/Desktop/po/local/lib/python2.7/site-packages/django/apps/registry.py", line 125, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

settings.py ::

    # Django settings for cope project.
import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG
PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

ADMINS = (
    ('pulkit', 'data.pulkit@gmail.com'),
    ('shashank', 'shashankgrovy@gmail.com'),
    ('sourabh', 'sourabh.coder@gmail.com'),
    ('utsav', 'kumaruts@gmail.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
         # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'cope.db',
        # Or path to database file if using sqlite3.
        # The following settings are not used with sqlite3:
        'USER': '',
        'PASSWORD': '',
        'HOST': '127.0.0.1',
        # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
        'PORT': '3306',
        # Set to empty string for default.
    }
}

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'Asia/Kolkata'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"

MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"

MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'

# Additional locations of static files
STATICFILES_DIRS = (
    os.path.join(os.path.join(PROJECT_PATH, 'cope'), 'static'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.FileSystemFinder',
    # 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = 'li=xy2zchjmi=)$+t$*yi5soc77yankx#=au+5&fy17_j3-#e%'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    # 'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'cope.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'cope.wsgi.application'

TEMPLATE_DIRS = (
    os.path.join(os.path.join(PROJECT_PATH, 'cope'), 'templates'),
)

DJANGO_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
)

LOCAL_APPS = (
    'opac',
    'transactions',
)

THIRD_PARTY_APPS = (
    'bootstrap_admin',
)

INSTALLED_APPS = THIRD_PARTY_APPS + LOCAL_APPS + DJANGO_APPS

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

populate_book.py ::

    import os
from random import randint
if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cope.settings")

from opac.models import Book, BookCopy

def make_isbn():
    return randint(1000000000000, 9999999999999)

titles = ['Gray Hat Python', 'Introduction to Algorithms', 'Pro Python',
    'HTML5 and JavaScript Projects', 'NginX HTTP Server', 'Redis Cookbook',
    'Python Fundamentals', 'Land of Lisp', 'Beginning iOS Game Development',
    'Ruby on Rails for Dummies', 'Django, AJAX and jQuery']

authors = ['Seitz', 'Thomas H. Corman', 'Marty Alchin', 'Geanie Mayer', 'Clement',
    'Tiago Macedo', 'Kent Lee', 'Courad', 'Patrick', 'Barry Burd', 'Jonathan Hayward']

publishers = ['No Starch Press', 'Stanford Press', 'Apress', 'Apress', 'Packt OpenSource',
    'O\'Reilly', 'Springer', 'No Starch Press', 'WROK', 'For Dummies', 'Packt OpenSource']

imageurls = ['grayhat.png', 'introtoalgo.png', 'propython.png', 'htmljs.png', 'nginx.png',
    'redis.png', 'pythonfundamentals.png', 'lisp.png', 'ios.png', 'ror.png', 'djangoajax.png']

def main():
    for i in range(len(titles)):
        isbn = make_isbn()
        new_book = Book(title=titles[i], isbn=isbn, ddc=randint(100,999), authors = authors[i],
            publisher=publishers[i], cost=randint(300,700), imageurl=imageurls[i], pages=randint(300,700))
        new_book.save()
        print '\n%4d | ISBN: %s | Title: %s' % (i+1, isbn, titles[i])
        for j in range(randint(5,10)):
            book_number = randint(50000,900000)
            book_copy = BookCopy(book_number=book_number, book_category=new_book)
            book_copy.save()
            print '%10d | Book Number: %-6d | Category: %s' % (j+1, book_number, new_book.title)

if __name__ == '__main__':
    main()

manage.py ::

    #!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cope.settings")

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

2 个答案:

答案 0 :(得分:1)

你应该确定的三件事,

  • 是您安装的INSTALLED_APPS设置中的所有应用 在你的系统上?
  • 您是否忘记激活virtualenv 哪里安装了一切?
  • 如果您的系统上面有上述两项内容,那么也许就是您 忘了在你的venv中安装应用程序中的应用程序?您可以通过pip install -r requirements.txt
  • 执行此操作

requirements.txt替换为您的要求文件的名称。确保在激活虚拟环境后执行此操作。

答案 1 :(得分:-1)