When I try to connect to handshake with my WebSocket, I'm getting the following error in Django terminal:
python3.12/site-packages/channels/routing.py", line 134, in __call__ raise ValueError("No route found for path %r." % path)ValueError: No route found for path 'ws/chat_app/3wVCio/'.WebSocket DISCONNECT /ws/chat_app/3wVCio/ [192.168.0.11:58136]I found, that in previous Django versions, the problem was, that instead of path, for defining the urlpatterns in this case, it should be used url(). However, the url() is depricated and instead of it, the re_path should be used. Unfortunately it did not help me..
Here is the routing, I created - routing.py
from django.urls import re_pathfrom .consumers import ChatConsumer# The WebSocket URL pattern for chat rooms is defined by this codewebsocket_urlpatterns = [ re_path(r'chat_app/(?P<unique_id>\w+)/$', ChatConsumer.as_asgi()),]This is the WebSocket consumer.py:
import jsonfrom channels.generic.websocket import AsyncWebsocketConsumerfrom asgiref.sync import sync_to_asyncfrom .models import Messagefrom room_app.models import Roomclass ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.unique_id = self.scope['url_route']['kwargs']['unique_id'] self.room_group_name = f'chat_{self.unique_id}' # Check if the room exists in the database if not await self.room_exists(): await self.close() return # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Save message to database Message.objects.create( room=self.unique_id, user=self.scope['user'], content=message ) # Send message to room group self.channel_layer.group_send( self.room_group_name, {'type': 'chat_message','message': message,'username': self.scope['user'].username } ) # Receive message from room group def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket self.send(text_data=json.dumps({'message': message,'username': username })) @sync_to_async def room_exists(self): return Room.objects.filter(unique_id=self.unique_id).exists()The way, that I have configured my project asgi.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')application = ProtocolTypeRouter({"http": get_asgi_application(),"websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ), ) })I have installed 'daphne' and added it into my settings.pyINSTALLED_APPS, where I have also defined my ASGI_APPLICATION and configured CHANNEL_LAYERS:
ASGI_APPLICATION = 'project.asgi.application'# Configure channel layersCHANNEL_LAYERS = {'default': {'BACKEND': 'channels_redis.core.RedisChannelLayer','CONFIG': {"hosts": [('192.168.0.11', 6379)], }, },}I have also included the websocket_urlpatterns in my project urls.py like so:
urlpatterns = [ path('admin/', admin.site.urls), ..., path('ws/', include(websocket_urlpatterns)),]