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

22

61

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.

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

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 :

import django
django.setup()

underneath this line :

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

as suggested from this post, but to no avail.

Here is my 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.clickjacking.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.

Kirwan answered 9/1, 2018 at 7:56 Comment(3)
There might be something in your portfolio_showcase app or root url config that is causing the problem. Don’t add django.setup() to settings.Forland
I had same problem - my issue was an unset environment variable - using postgresql with django-environ and DATABASE_URL wasn't set - setting that fixed it for me.Boldfaced
I've seen this error in the past. IIRC it had to do with a migration file that depended on the migration of a 3rd party module. I hadn't defined the migration dependencies correctly.Hollow
G
61

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.

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

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

os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true"
Greathouse answered 2/6, 2018 at 6:25 Comment(3)
Those 2 last lines were enough in my situation. I added them into my projectname/projectname/__init__.py so they get always executed before anything in my apps.Eckert
As the 4 lines correspond to the wsgi.py file content (like mentioned in the answer), you can also just do import your_project.wsgi.py in any standalone python file to get your django modules bootstrapped. (For example useful for trying out snippets)Succuss
Those 2 last lines were also enough in my situation, that is, "from django.core.wsgi import get_wsgi_application" and "application = get_wsgi_application()". I had to put the 2 lines in ABOVE the import line that caused the error.Scrannel
J
34

Please run check django-admin command to see if it have detected any errors.

python manage.py check

and/or

django-admin check
Judiejudith answered 20/2, 2018 at 13:50 Comment(5)
In my case it was an empty SECRET_KEY env variablePanarabism
A very unhelpful message for a non existent secret keyGrodno
What should we do if python manage.py check runs OK, but django-admin check complains about some constant not set, say USE_I18N?Gearard
In my case, running this raises the exact same "Apps aren't loaded" error - ha.Browder
A +1 for this answer seems not enough. ThanksExperimentation
P
9

My problem was that I was trying to import before the setup was ran. Here's my solution: make the import after the 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!!
Protege answered 14/8, 2019 at 11:4 Comment(3)
This just ended two hours of frustration. Thank you so muchKaryotype
might be a stupid question, but where do I need to put this code?Outwards
This is an example on how to import the django configuration + use it. So you can use this piece of code in your own python file, for example if you need to run your own tests or make a small "disposable" piece of code (import some stuff or whatever)Protege
A
7

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.

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.

Allare answered 9/1, 2018 at 12:35 Comment(0)
D
4

In your wsgi.py or asgi.py as the case may be

have these lines before anything else

import os 
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

import django
django.setup()
Diaphaneity answered 18/8, 2021 at 13:6 Comment(1)
this is the right answer imhoPerambulate
L
3

Just import inside ready() method:

def ready(self):
    print('Sent From ready')
    from django.db.models.signals import post_save
    from yourapp.api.signals import post_save_user_receiver
    post_save.connect(post_save_user_receiver, sender=settings.AUTH_USER_MODEL)
Leucippus answered 20/9, 2020 at 6:9 Comment(0)
B
2

Just in case it helps someone: my issue was that I was importing some classes, functions and variables into the __init__ file of the app's folder.

It work as expected after I empty the __init__ file.

Biodegradable answered 6/1, 2021 at 22:49 Comment(0)
M
2

I had similar problem with Apps aren't loaded yet. in Django 2.0

Problem was started here with importing modules outside def ready()

from django.apps import AppConfig

from django.contrib.auth.models import User
from django.db.models.signals import post_delete
from .signals import post_delete_msg

class ProductionAppConfig(AppConfig):
    name = 'production_app'

    def ready(self):
        post_delete.connect(post_delete_msg, sender=User)

solved by moving imports to def ready()

from django.apps import AppConfig
    
class ProductionAppConfig(AppConfig):
    name = 'production_app'

    def ready(self):
        from django.contrib.auth.models import User
        from django.db.models.signals import post_delete
        from .signals import post_delete_msg
        post_delete.connect(post_delete_msg, sender=User)
        
Milkweed answered 28/8, 2022 at 15:51 Comment(0)
H
2
import django
django.setup()

This worked for me...I tried everything and at last moment, this two lines solved my issue.

Heger answered 16/2, 2023 at 17:39 Comment(0)
L
1

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

  1. Check if you have initialised SECRET_KEY in it.
  2. Check if you have application in INSTALLED_APPS and is not installed.
Lorenza answered 14/6, 2018 at 6:42 Comment(0)
L
1

First at all: check if you have the same code like below in yourproject.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.

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

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.

Landgraviate answered 28/8, 2019 at 15:23 Comment(0)
M
0

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.

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
./manage.py makemigrations --settings=djangoproject.settings.development
./manage.py migrate --settings=djangoproject.settings.development
Mcgannon answered 25/1, 2019 at 18:44 Comment(0)
F
0

In my case it was a missing python package which was in use in the application that caused the issue.

So check if all applications / packages in use are effectively installed in your python (virtual) environment.

The applications you can find in the INSTALLED_APPS (see your settings.py file).

Python packages can be used anywhere in your code so can be more difficult to trace down. But usually the error message will hint at the missing package as well.

Fogged answered 3/11, 2020 at 10:26 Comment(0)
I
0

I uninstalled and reinstalled Django to fix this issue. pip uninstall django

Then pip install django.

Note: install the same django version as before.

Ineptitude answered 20/8, 2021 at 8:44 Comment(0)
M
0

make sure everything in your app runs after apps.py. check to not importing any module in apps.py except AppConfig (or any django bult in module)

Morell answered 6/1, 2022 at 18:11 Comment(0)
L
0

Try to change DEBUG settings to False

DEBUG = False

This solved my error

Lightyear answered 22/8, 2022 at 22:28 Comment(0)
H
0

Happened to me when I did

from unittest import TestCase, mock

instead of

from unittest import mock

from django.test import TestCase

in my test file

Holograph answered 24/8, 2022 at 12:25 Comment(0)
V
0

place this on the top of the "asgi.py" file (there are conflicts between jwt auth, because it is accessing the user model before get_asgi_application function):

django_asgi_app = get_asgi_application()
Veinlet answered 25/1, 2023 at 1:8 Comment(0)
P
0

Make sure there are no broken imports at the beginning of your settings.py file. Hope this answer saves someone's day

Pyongyang answered 3/6, 2023 at 13:3 Comment(2)
Can you elaborate? What is a "broken import"?Illmannered
Basically a broken import is an import pointing to a library that does not exist or that does not exist anymore. The settings.py file does not throw import errors to notify that a library is not available, it will instead stop loading the informations (Installed apps, middlewares, etc..) that follow the broken import statement.Pyongyang
W
0

In my case,This error message was caused because of an unused import in the core/settings.py file.

NOTE: Delete unused imports in you project main settings file.

Whittier answered 15/9, 2023 at 8:50 Comment(0)
H
0

My resolution was very hard to track down but it ended up being the inclusion of the django_extensions library in INSTALLED_APPS which may be specific to running on AWS Lambda through Zappa.

I've since added this to my settings.py:

if DEBUG:
    INSTALLED_APPS += ("django_extensions",)
Houseleek answered 11/1 at 15:3 Comment(0)
P
0

I faced the same issue. In my case, I'm utilizing channels and Daphne to employ websockets. In routing.py, I import consumers.py.

from django.urls import path
from . import consumers

websocket_urlpatterns = [
    path('ws/socket-server', consumers.SocketConsumer.as_asgi())
]

Within consumers.py, I import my model:

from .models.File import MyFile

The solution was to add at the top of the file (consumers.py):

import django
django.setup()
Pentathlon answered 28/2 at 7:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.