Class() got an unexpected keyword argument 'unique_id', when trying to connect to a WebSocket
I'm trying to connect to my Django WebSocket, but I keep getting the following exception:
TypeError: ChatConsumer() got an unexpected keyword argument 'unique_id'
"GET /ws/chat_app/sjfAmH/ HTTP/1.1" 500 64965
I'm basically following a tutorial and that is how the guy does it in there. I have also looked at other implementations and I find it as the same way.. I'm new at using WebSockets, I would appreciate any kind of help. Thanks in advance!
This is my ChatConsumer class:
# chat/consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
from .models import Message
from room_app.models import Room
class 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()
This is the WebSocket url pattern, I have defined in my routing.py:
from django.urls import re_path
from .consumers import ChatConsumer
# The WebSocket URL pattern for chat rooms is defined by this code
websocket_urlpatterns = [
re_path(r'chat_app/(?P<unique_id>\w+)/$', ChatConsumer.as_asgi()),
]
Then, I have added that to my Django project urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
...,
path('ws/', include(websocket_urlpatterns)),
]
I'm trying to access this endpoint in my browser like so:
If needed, in my Flutter app, I'm trying to access it like so:
_channel = IOWebSocketChannel.connect(Uri.parse(
'ws://192.168.0.11:8000/ws/chat_app/${room.uniqueID}'));
Update:
I have tried defining __init__ method to that class, like so:
def __init__(self, *args, **kwargs):
self.unique_id = kwargs.pop('unique_id', None)
super().__init__(*args, **kwargs)
and configuring my project asgi.py file like so:
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from chat_app.routing import websocket_urlpatterns
from channels.security.websocket import OriginValidator
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
application = ProtocolTypeRouter({
"http": get_asgi_application(), # Django HTTP ASGI application
"websocket": OriginValidator(
AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
),
['*']
)
), # Django Channels WebSocket ASGI application
})
Did not help.