I get the error "Apps aren't loaded yet." when publishing with Daphne

When I try to publish my project with daphne, which runs smoothly while running on the development server, I get the following output.

(venv) C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog> daphne -b 0.0.0.0:8000 myblog.asgi:application
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Scripts\daphne.exe\__main__.py", line 7, in <module>
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\cli.py", line 171, in entrypoint
    cls().run(sys.argv[1:])
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\cli.py", line 233, in run
    application = import_by_path(args.application)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\utils.py", line 17, in import_by_path
    target = importlib.import_module(module_path)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1204, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1176, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\myblog\asgi.py", line 8, in <module>
    from socketchat.routing import websocket_urlpatterns
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\socketchat\routing.py", line 4, in <module>
    from socketchat import consumers
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\socketchat\consumers.py", line 7, in <module>
    from socketchat.models import Message, ConversationSocket
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\socketchat\models.py", line 3, in <module>
    from userapp.models import User
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\userapp\models.py", line 2, in <module>
    from django.contrib.auth.models import AbstractUser
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\contrib\auth\models.py", line 3, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\contrib\auth\base_user.py", line 59, in <module>
    class AbstractBaseUser(models.Model):
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\db\models\base.py", line 129, in __new__
    app_config = apps.get_containing_app_config(module)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\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.

here is my installed apps

INSTALLED_APPS = [
    # 3rd party apps
    'daphne',
    'rest_framework',
    'channels',
    'psycopg',
    
    # my apps
    'userapp',
    'blogs',
    'pages',
    'socketchat',
    
    # Django apps
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sitemaps',
]

my asgi.py file;

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

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
from socketchat.routing import websocket_urlpatterns


application = ProtocolTypeRouter(
    {
        "http": get_asgi_application(),
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

What I have difficulty understanding is that everything is normal on the development server, but when I want to run it with daphne, it says that the applications are not installed. By the way forgive me if my English is bad.

That’s not actually what it’s saying here. It’s not saying that the applications are not installed, it’s saying that the applications haven’t been loaded yet when something is trying to use them.

There’s a specific process that Django goes through when it starts, and if things happen out-of-order, then problems occur.

In this case, I believe the issue may be that you have your get_asgi_application function call in the ProtocolTypeRouter class definition.

See the code at Tutorial Part 2: Implement a Chat Server — Channels 4.1.0 documentation, for the asgi.py file, and do not try to reorganize it.

Actually, before you said that, I thought it might be related to this, but I haven’t found an exception yet. I’m attaching below the contents of the routing.py file where I imported the websocket_urlpatterns;

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

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
from socketchat.routing import websocket_urlpatterns


application = ProtocolTypeRouter(
    {
        "http": get_asgi_application(),
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

What I was trying to point out is that the tutorial shows this:

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()
                  ^^^^^^^^^^^^^^^^^^^^

from chat.routing import websocket_urlpatterns

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

But you have this:

Which is causing the get_asgi_application function to be called at a different point in time.

Try changing your asgi.py to match exactly the sequence of events as presented in the tutorial.

Actually, I think one of the process order in the tutorial is loaded in the wrong order, when I load os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “myblog.settings”) according to the order in the tutorial I get the error “django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.” If the error is related to this, I can’t figure out how else to solve it. Also, you mentioned " django_asgi_app = get_asgi_application()"
I edited it but the result didn’t change.

Please show your current asgi.py.

Side note: The tutorial is correct. That asgi.py file works exactly as-is when used in the context of the tutorial.

asgi.py file

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

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
from socketchat.routing import websocket_urlpatterns

django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

Yes the tutorial normally works correctly. I can run python manage.py with runserver without any problem but I can’t run it with daphne. This is the situation that challenges my logic…

This is still not the order shown in the tutorial.

And, if it’s not working, please post the complete error message with the traceback.

organized according to the order in education;

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
from socketchat.routing import websocket_urlpatterns

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


django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

this is the error output

(venv) C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog> daphne -b 0.0.0.0:8000 myblog.asgi:application
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Scripts\daphne.exe\__main__.py", line 7, in <module>
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\cli.py", line 171, in entrypoint
    cls().run(sys.argv[1:])
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\cli.py", line 233, in run
    application = import_by_path(args.application)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\utils.py", line 17, in import_by_path
    target = importlib.import_module(module_path)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1204, in _gcd_import        
  File "<frozen importlib._bootstrap>", line 1176, in _find_and_load     
  File "<frozen importlib._bootstrap>", line 1147, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 690, in _load_unlocked      
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\myblog\asgi.py", line 7, in <module>
    from socketchat.routing import websocket_urlpatterns
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\socketchat\routing.py", line 4, in <module>
    from socketchat import consumers
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\socketchat\consumers.py", line 7, in <module>
    from socketchat.models import Message, ConversationSocket
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\socketchat\models.py", line 3, in <module>
    from userapp.models import User
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\userapp\models.py", line 2, in <module>
    from django.contrib.auth.models import AbstractUser
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\contrib\auth\models.py", line 3, in <module>      
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\contrib\auth\base_user.py", line 59, in <module>  
    class AbstractBaseUser(models.Model):
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\db\models\base.py", line 129, in __new__
    app_config = apps.get_containing_app_config(module)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\apps\registry.py", line 137, in check_apps_ready  
    settings.INSTALLED_APPS
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\conf\__init__.py", line 89, in __getattr__        
    self._setup(name)
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\conf\__init__.py", line 69, in _setup
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Normally those who get this error export DJANGO_SETTINGS_MODULE with cli from outside as far as I can see

Please post the complete contents of your socketchat routing.py file.

routing.py file;

# chat/routing.py
from django.urls import re_path

from socketchat import consumers

websocket_urlpatterns = [
    re_path(r'^ws/socketchat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer.as_asgi()),
]

Your asgi.py still doesn’t match the order of the tutorial.

In the tutorial, the line

appears before the import of the websocket_urlpatterns, not after.

I think you mean this way

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
django_asgi_app = get_asgi_application()

from socketchat.routing import websocket_urlpatterns

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



application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

error output changed

(venv) C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog> daphne -b 0.0.0.0:8000 myblog.asgi:application
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Scripts\daphne.exe\__main__.py", line 7, in <module>
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\cli.py", line 171, in entrypoint
    cls().run(sys.argv[1:])
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\cli.py", line 233, in run
    application = import_by_path(args.application)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\daphne\utils.py", line 17, in import_by_path
    target = importlib.import_module(module_path)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\myblog\asgi.py", line 8, in <module>
    django_asgi_app = get_asgi_application()
                      ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\core\asgi.py", line 12, in get_asgi_application
    django.setup(set_prefix=False)
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
                      ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\conf\__init__.py", line 89, in __getattr__
    self._setup(name)
  File "C:\Users\Fahri\Desktop\Django Projects\My Examples\myblog\venv\Lib\site-packages\django\conf\__init__.py", line 69, in _setup
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Nope. Still doesn’t match.

The sequence of the four key statements:

  1. from django.core.asgi import get_asgi_application

  2. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

  3. django_asgi_app = get_asgi_application()

  4. from chat.routing import websocket_urlpatterns

1 Like

Really thank you very much, I guess I was not looking in the right place in the tutorial because the order you gave and the order in the tutorial are not the same. I am attaching the working codes here;

import os

from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myblog.settings")
django_asgi_app = get_asgi_application()
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator

from socketchat.routing import websocket_urlpatterns




application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

Here are the codes on https://channels.readthedocs.io/ that I think are wrong;

# mysite/asgi.py
import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()

from chat.routing import websocket_urlpatterns

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
        ),
    }
)

How is what you’re quoting different from what I posted? (Hint, it’s not. What I posted was extracted directly from the tutorial.)

What I posted:

What you copied, annotated with the numbers used above:

# mysite/asgi.py
import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator

### 1 ###
from django.core.asgi import get_asgi_application

### 2 ###
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.

### 3 ###
django_asgi_app = get_asgi_application()

### 4 ###
from chat.routing import websocket_urlpatterns

...

Now I understand better that I was wrong all along. The get_asgi_application in the first and third rows confused me and I thought it was wrong. Your attention is appreciated. Thanks again and again :slight_smile: