Bird
0
0

Identify the error in this consumer code snippet: ```python class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'chat_room' await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) ```

medium📝 Debug Q6 of 15
Django - Async Django
Identify the error in this consumer code snippet: ```python class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'chat_room' await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) ```
AMissing import for channel_layer
Bchannel_layer is not defined in the consumer
Cgroup_add and group_discard methods require await
DNo receive method defined to handle messages
Step-by-Step Solution
Solution:
  1. Step 1: Check channel_layer usage

    The code uses self.channel_layer but does not define or import channel_layer.
  2. Step 2: Understand channel_layer access

    channel_layer is available as self.channel_layer in consumers if ASGI is configured properly; if missing, it causes error.
  3. Final Answer:

    channel_layer is not defined in the consumer -> Option B
  4. Quick Check:

    channel_layer must be accessible as self.channel_layer [OK]
Quick Trick: Ensure self.channel_layer is available before group operations [OK]
Common Mistakes:
MISTAKES
  • Assuming group_add doesn't need await
  • Ignoring missing channel_layer setup
  • Thinking receive method is mandatory for connect/disconnect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes