Bird
0
0

In Django Channels, to broadcast a message to all WebSocket clients connected to the group 'chat_room', which of the following sequences is correct inside a consumer method?

hard📝 Application Q8 of 15
Django - Async Django
In Django Channels, to broadcast a message to all WebSocket clients connected to the group 'chat_room', which of the following sequences is correct inside a consumer method?
Aawait self.channel_layer.group_add('chat_room', self.channel_name); await self.send(text_data='Hello')
Bawait self.send(text_data='Hello'); await self.channel_layer.group_send('chat_room', {'type': 'chat_message', 'message': 'Hello'})
Cawait self.channel_layer.group_send('chat_room', {'type': 'chat_message', 'message': 'Hello'}); async def chat_message(self, event): await self.send(text_data=event['message'])
Dawait self.channel_layer.group_send('chat_room', 'Hello')
Step-by-Step Solution
Solution:
  1. Step 1: Use group_send to send to all group members

    The method group_send requires the group name and a message dict with a 'type' key specifying the handler method.
  2. Step 2: Define the handler method

    The 'type' value corresponds to a method name (chat_message) that receives the event and sends the message to the WebSocket client.
  3. Step 3: Verify the message sending

    Inside chat_message, use await self.send(text_data=event['message']) to send the message to the client.
  4. Final Answer:

    await self.channel_layer.group_send('chat_room', {'type': 'chat_message', 'message': 'Hello'}); async def chat_message(self, event): await self.send(text_data=event['message']) correctly implements broadcasting to the group.
  5. Quick Check:

    group_send needs type and handler method [OK]
Quick Trick: Use group_send with type and handler method [OK]
Common Mistakes:
MISTAKES
  • Calling send instead of group_send for broadcast
  • Omitting the 'type' key in group_send message
  • Not defining the handler method matching 'type'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes