django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I don’t know why the error occurs… help me please

error

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1073, in _bootstrap_inner
    self.run()
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\threading.py", line 1010, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run    
    autoreload.raise_last_exception()
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 398, in execute
    autoreload.check_errors(django.setup)()
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
                 ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\apps\config.py", line 178, in create
    mod = import_module(mod_path)
          ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 935, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 994, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "C:\Users\nori\Envs\kingwangjjang-be\kingwangjjang\webCrwaling\models.py", line 4, in <module>
    class UserInfo(models.Model):
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\models\base.py", line 127, in __new__
    app_config = apps.get_containing_app_config(module)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\nori\AppData\Local\Programs\Python\Python312\Lib\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.
# prj/app/models.py
from djongo import models

class UserInfo(models.Model):
    userName = models.CharField(max_length=100)
    age = models.IntegerField()
    sex = models.CharField(max_length=10)

    def __str__(self):
        return self.userName

settings.py

"""
Django settings for kingwangjjang project.

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

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

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

from pathlib import Path

# 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/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
import os, json
from django.core.exceptions import ImproperlyConfigured

# Local settings
secret_file = os.path.join(BASE_DIR, './secrets.json') 

with open(secret_file) as f:
    secrets = json.loads(f.read())

def get_secret(setting, secrets=secrets):
    try:
        return secrets[setting]
    except KeyError:
        error_msg = "Set the {} environment variable".format(setting)
        raise ImproperlyConfigured(error_msg)

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
SECRET_KEY = get_secret('SECRET_KEY')
DB_HOST = get_secret("DB_HOST")
DB_USER = get_secret("DB_USER")
DB_PASSWORD = get_secret("DB_PASSWORD")
DB_NAME = get_secret("DB_NAME")

# # github action setting
# SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
# DEBUG = os.environ.get('DJANGO_DEBUG', 'False') == 'True'
# DB_HOST = os.environ.get('DB_HOST')
# DB_USER = os.environ.get('DB_USER')
# DB_PASSWORD = os.environ.get('DB_PASSWORD')
# DB_NAME = os.environ.get('DB_NAME')



ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'graphene_django',
    'graphene_mongo',
    'webCrwaling',
    'kingwangjjang',
    'webCrwaling.models.UserInfo',
]

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',
    # 'webCrwalling.userInfo',
    # 'graphene_django',
]

ROOT_URLCONF = 'kingwangjjang.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 = 'kingwangjjang.wsgi.application'

# Database
# MongoDB settings
DB_URI = 'mongodb://'+ DB_HOST + '/' + DB_USER + ':' + DB_PASSWORD
DATABASES = {
        'default': {
            'ENGINE': 'djongo',
            'NAME': DB_NAME,
            'ENFORCE_SCHEMA': False,
            'CLIENT': {
                'host': DB_URI
            }  
        }
}

# Password validation
# https://docs.djangoproject.com/en/5.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/5.0/topics/i18n/

LANGUAGE_CODE = 'ko-kr'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

GRAPHENE = {
    "SCHEMA": "webCrwaling.schema.schema"
}

This is my first time using Django and I am a beginner. Please let me know how to solve it and I will find out.

thank you :heart:

Generally speaking, this type of error is tough to generalize. It’s usually caused by trying to perform an operation at the module level instead of within a function. Finding the actual cause then usually requires looking at everything in the project.

What are the contents of your “prj/app/apps.py” file?

First of all, thank you for your reply.

When I ran “startapp”, apps.py was not created so I did not use it. There is no apps.py, but views.py.

import json
import requests 
from bs4 import BeautifulSoup 
from django.http import JsonResponse
from selenium import webdriver
from urllib import request as urllib_request

from mongo import DBController  

# Create your views here.


def CommunitySiteCrawler(request):
    db_controller = DBController()
    collection_name = "pymongotest"
    data_to_insert = {
    "userName": "Bob",
    "age": 25,
    "sex": "male"
    }

    result = db_controller.insert(collection_name, data_to_insert)
    return JsonResponse({"a": "a"})

There is one thing I did not write in the post. The cause is an error that occurred while adding graphql.

This is the code generated when adding graphql.

# prj/app/admin.py
from django.contrib import admin
from webCrwaling.models import UserInfo

admin.site.register(UserInfo)
# prj/app/models.py
from djongo import models

class UserInfo(models.Model):
    userName = models.CharField(max_length=100)
    age = models.IntegerField()
    sex = models.CharField(max_length=10)

    def __str__(self):
        return self.userName
# prj/schema.py

import graphene
from graphene_django.types import DjangoObjectType
from webCrwaling.models import UserInfo

class YourModelType(DjangoObjectType):
    class Meta:
        model = UserInfo

class Query(graphene.ObjectType):
    your_model = graphene.Field(YourModelType, id=graphene.Int())

    def resolve_your_model(self, info, id):
        return UserInfo.objects.get(pk=id)

schema = graphene.Schema(query=Query)

thank you.

So there’s something being done within the graphene module (the Schema initializer) that is trying to create an instance of the Query class. This means that you cannot use that statement at the module level within your application. You need to find some other way to do this. (I’d have no idea what that “other way” may be. I don’t use either djongo or graphene with Django.)

Let’s find another way. Thank you very much for your reply.