Complete the code to import the Channels layer for WebSocket support.
from channels import [1]
The routing module is imported from Channels to define WebSocket URL routes.
Complete the code to define a WebSocket consumer class inheriting from the correct Channels base class.
from channels.generic.websocket import [1] class ChatConsumer([1]): pass
AsyncWebsocketConsumer is the recommended base class for asynchronous WebSocket consumers in Channels.
Fix the error in the routing configuration by completing the WebSocket URL pattern.
from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<[1]>[^/]+)/$', consumers.ChatConsumer.as_asgi()), ]
The URL pattern uses room_name as the named group to capture the chat room identifier.
Fill both blanks to complete the async method that accepts a WebSocket connection and adds the user to a group.
async def connect(self): self.room_group_name = f'chat_[1]' await self.channel_layer.[2]( self.room_group_name, self.channel_name ) await self.accept()
The room_name variable is used to create the group name string. The group_add method adds the channel to the group.
Fill all three blanks to complete the async method that receives a message and sends it to the group.
async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.[1]( self.room_group_name, { 'type': '[2]', 'message': message } ) async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps([3]))
The group_send method sends a message to the group. The type specifies the handler method chat_message. The send method sends the JSON message back to the WebSocket client.