[Django]-Django apps aren't loaded yet when using asgi

12👍

Before using Django infrastructure in standalone application you should always do django.setup()

So, your asgi.py should be like

import os
from channels.routing import get_default_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
django.setup()
application = get_default_application()

48👍

For anyone using Django > 3.0 refer to link below. It worked for me

https://github.com/django/channels/issues/1564#issuecomment-722354397

all you have to do is to call get_asgi_application() before importing anything else

Sample of my asgi.py file:

import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
django_asgi_app = get_asgi_application()

from django.conf import settings
from .routing import asgi_routes

asgi_routes["http"] = django_asgi_app
application = ProtocolTypeRouter(asgi_routes)

5👍

It turned out that django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet error in Channels lib, happened due to invalid import order in my application – as explained here.

Cause:

I imported my WSAccessTokenAuthMiddleware before importing my instance of django_asgi_app.

Solution:

Importing my django_asgi_app before WSAccessTokenAuthMiddleware fixed the problem.

# First, import app created by get_asgi_application() - django.core.asgi
from general.settings.asgi import application as django_asgi_app

# Second, import my middleware and consumers
from general.consumers import ModelConsumer
from general.util.auth import WSAccessTokenAuthMiddleware

# Third, Import channels classes
from django.conf.urls import url
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter
from channels.routing import URLRouter


application = ProtocolTypeRouter({
    "http": django_asgi_app,
    'websocket': WSAccessTokenAuthMiddleware(
        AuthMiddlewareStack(
            URLRouter([
                url('ws/models/(?P<model_name>\w+)', ModelConsumer.as_asgi()),
            ])
        )
    )
})

Leave a comment