Django Channels throwing raise ImproperlyConfigured(“Cannot import ASGI_APPLICATION module %r” % path) error

I am working on a Django project that uses Django Channels, Daphne, and Django Tenants for multitenancy and WebSocket communication. My project structure includes a project folder and several application folders.

In the project folder, I have the usual files like asgi.py, wsgi.py, settings.py, and consumers.py (for handling Django Channels). I am not using routing.py. In the application folder, I have files like models.py, serializers.py, views.py, and urls.py.

The WebSocket communication works fine, but I encounter an issue when trying to import a service module in consumers.py.

asgi.py

import os
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.urls import path, re_path
from .consumers import ABConsumer
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'autobiz.settings')
import django
django.setup()
# 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()

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    # Just HTTP for now. (We can add other protocols later.).
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                #path("ws/admin/", ABConsumer.as_asgi()),
                re_path(r'ws/server/(?P<tenant_name>w+)/$', ABConsumer.as_asgi()),
            ])
        )
    ),
})

consumers.py

from channels.generic.websocket import AsyncWebsocketConsumer
import json
import logging
**from autobiz.abshared.services import process_token
**
# Setting up logging
logger = logging.getLogger(__name__)


class ABConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        # Get tenant name from the URL
        self.tenant_name = self.scope['url_route']['kwargs']['tenant_name']  # Extract tenant name from URL route
        self.room_name = f'{self.tenant_name}_room'  # Create a tenant-specific room name
        self.room_group_name = f'chat_{self.room_name}'

        logger.info(f"Connection attempt from tenant: {self.tenant_name}")

        # Join the tenant-specific room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        # Accept the WebSocket connection
        await self.accept()

    async def receive(self, text_data=None, bytes_data=None):
        # Handle incoming message (text or binary)
        if text_data:
            logger.info(f"Received text data from tenant {self.tenant_name}: {text_data}")
            response = {
                'tenant': self.tenant_name,
                'message': f'{text_data}'
            }

            # Perform the import inside the method to avoid circular import issues

            # Send the message to the room group (broadcast to all clients in the room)
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': json.dumps(response)  # Convert response to JSON
                }
            )
        elif bytes_data:
            logger.info(f"Received binary data from tenant {self.tenant_name}.")
            await self.send(bytes_data=b'Server received binary data')

    async def chat_message(self, event):
        # Send the broadcast message back to WebSocket clients
        message = event['message']

        # Send the message to the WebSocket connection
        await self.send(text_data=message)

    async def disconnect(self, close_code):
        # Leave the tenant-specific room group when the socket closes
        logger.info(f"Disconnected from tenant {self.tenant_name} with code: {close_code}")

        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

In my settings.py ASGI setting is:

ASGI_APPLICATION = 'autobiz.asgi.application'

After running the ASGI server, everything works fine until I add this line to consumers.py:

from autobiz.abshared.services import process_token

When I add the import statement, I get the following error:

 raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'autobiz.asgi'

  • autobiz is my project name.
  • abshared is my app name.
  • services.py is located inside the abshared app.
    What I’ve Tried:
    Downgrading Django, Channels, and Redis-Channels versions.
    Adding import django; django.setup() in asgi.py.
    Verifying the default environment settings.
    Ensuring the path to the services.py file is correct.
    None of these solutions have worked, and the issue persists. It seems that Django is not finding the correct path for the services.py file, while other imports work just fine.

Expectation:
I expect Django to properly resolve the path to the services.py file in the same way other imports are working. Any suggestions on how to fix this error would be greatly appreciated!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật