Django. Apps are not loaded yet

Feature(s) impacted

I get this error django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet when trying to start a django server with forestadmin.

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
    autoreload.raise_last_exception()
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 398, in execute
    autoreload.check_errors(django.setup)()
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/apps/config.py", line 228, in create
    import_module(entry)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 848, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django_forest/__init__.py", line 3, in <module>
    from django_forest.utils.schema import Schema
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django_forest/utils/schema/__init__.py", line 29, in <module>
    class Schema:
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django_forest/utils/schema/__init__.py", line 36, in Schema
    'database_type': connection.vendor,
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/utils/connection.py", line 15, in __getattr__
    return getattr(self._connections[self._alias], item)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/utils/connection.py", line 62, in __getitem__
    conn = self.create_connection(alias)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/db/utils.py", line 208, in create_connection
    backend = load_backend(db["ENGINE"])
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/db/utils.py", line 113, in load_backend
    return import_module("%s.base" % backend_name)
  File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django_tenants/postgresql_backend/base.py", line 8, in <module>
    from django.contrib.contenttypes.models import ContentType
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/contrib/contenttypes/models.py", line 131, in <module>
    class ContentType(models.Model):
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config
    self.check_apps_ready()
  File "/home/watrhub/PycharmProjects/MehorPlatform/backend/venv/lib/python3.8/site-packages/django/apps/registry.py", line 138, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Observed behavior

When trying to start the django server with manage.py runserver I get the same error: Apps aren't loaded yet.

Django AppRegistryNotReady("Models aren't loaded yet.") when deploying on heroku - putting init_forest() after or before application=get_wsgi_application() in wsgi.py DOESN’T HELP.

Setup

Django version - 4.0.6
django-forestadmin - 1.4.4

Configuration

wsgi.py

import os

from django.core.wsgi import get_wsgi_application
from django_forest import init_forest

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


application = get_wsgi_application()
init_forest() 

settings.py

***

INSTALLED_APPS = [
    "django_forest",
    "django.contrib.admin",
    "django_tenants",
    "rest_framework",
    ...

]

DATABASE_ROUTERS = ("django_tenants.routers.TenantSyncRouter",)

FOREST = {
    "FOREST_URL": "https://api.forestadmin.com",
    "FOREST_ENV_SECRET": "",
    "FOREST_AUTH_SECRET": "",
}
APPEND_SLASH = False

url.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    ***,
    path("forest", include("django_forest.urls")),
]

Hi @Danil_Redko,

Yours is a tricky one. I have tried to reproduce the error but to no avail. Would you be able to share more info on our setup/stack/dev environment ?

Is the error occuring on localhost (in dev environment) ? Or only when you push to remote ? Or both I guess ?

Is that an existing project or did you try to update one ?

Thanks for your input,

Regards,

@Nicolas.M

Hey @Nicolas.M,

Thank you for trying to reproduce it.

I’m more than happy to provide any additional information, what kind of info about my stack would you need?

It’s the first time trying to set up django forest, so it’s a new project.

Yes, it happens on both(localhost and remote).

The whole settings.py file

from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")


# Application definition

SHARED_APPS = [
    # "django_forest",
    "django_tenants",
    "customers",
    "rest_framework",
    "corsheaders",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "admin_totals",
]
TENANT_APPS = [
    "fooditems",
    "loyalty",
    "customer_settings",
    "whatsapp",
    "webhook",
    "marketing",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]


INSTALLED_APPS = list(SHARED_APPS) + [
    app for app in TENANT_APPS if app not in SHARED_APPS
]
TENANT_MODEL = "customers.Client"
TENANT_DOMAIN_MODEL = "customers.Domain"

FOREST = {
    "FOREST_URL": "https://api.forestadmin.com",
    "FOREST_ENV_SECRET": "",
    "FOREST_AUTH_SECRET": "",
}
APPEND_SLASH = False


MIDDLEWARE = [
    "django.middleware.common.CommonMiddleware",
    "django_tenants.middleware.main.TenantMainMiddleware",
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "corsheaders.middleware.CorsMiddleware",
]

ROOT_URLCONF = "MehorPlatform.urls"
PUBLIC_SCHEMA_URLCONG = "MehorPlatform.public_urls"

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


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASE_ROUTERS = ("django_tenants.routers.TenantSyncRouter",)


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 = "America/Toronto"

USE_I18N = True

USE_TZ = True


GS_QUERYSTRING_AUTH = False
GS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage"
GS_BUCKET_NAME = "plaform_pilot_bucket"

MEDIA_URL = "/media/"
STATIC_URL = "/django_static/"
STATIC_ROOT = BASE_DIR / "django_static"

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
SHOW_PUBLIC_IF_NO_TENANT_FOUND = True

CORS_ALLOW_ALL_ORIGINS = True

I was playing around more with, if I remove “django-forest” from the list of INSTALLED APPS, it started to work in dev environment and I can connect to Forest Admin successfully with no "Apps are not loaded yet" error.

@Nicolas.M @jeffladiray

The solution that I found was to REMOVE “django-forest” from INSTALLED_APPS list. From that point everything works fine.
I guess it’s incorrect way of setting up the app, but I couldn’t find any other way to make it work. Ready to provide any additional information if asked!

Thank you!