You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Channels报错:未找到app_consumer.notification_message消息处理器

解决"No handler for message type app_consumer.notification_message"错误

这个问题的核心原因是你在发送WebSocket群组消息时,指定的type格式不符合Channels的要求。

错误原因详解

Channels中,group_send里的type字段需要对应你WebsocketConsumer类中定义的方法名,格式必须是纯下划线分隔的小写字符串。你现在用的"app_consumer.notification_message"会被Channels自动转换为app_consumer_notification_message去查找对应的方法,但你的AppConsumer类里只有notification_message方法,所以系统找不到匹配的处理器,就抛出了这个错误。

修复步骤

1. 修改模型接收器中的type字段

打开你的接收器代码,把group_send中的type值改为直接对应方法名:

@receiver(pre_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, update_fields=None, **kwargs):
    if update_fields:
        if 'pan_number_verified' in update_fields and instance.pan_number_verified is True:
            notification = Notification.objects.create(message='Your PAN Number has been verified...Head on to creating a campaign right away.', user=instance)
            channel_layer = get_channel_layer()
            async_to_sync(channel_layer.group_send)(
                "notification_%s" % instance.id, 
                {
                    "type": "notification_message",  # 这里修改为方法名
                    "message": str(notification.id)
                }
            )

2. 同步修改AppConsumer中receive方法的type字段

你的Consumer里的receive方法也用了错误的type格式,同样需要修改:

class AppConsumer(WebsocketConsumer):
    # ... 其他方法保持不变 ...

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'notification_message',  # 这里也修改为方法名
                'message': message
            }
        )

    # ... notification_message方法保持不变 ...

额外验证点

  • 确认用户连接的room_group_name(即notification_{user_id})和接收器中发送的群组名称完全一致
  • 确保channel_layer已经正确配置(比如使用Redis作为后端,并且配置无误)
  • 检查Notification模型的创建逻辑是否正常,确保instance.id是有效的用户ID

这样修改后,Channels就能正确找到notification_message方法来处理你的WebSocket消息了。

内容的提问来源于stack exchange,提问作者Goutam B Seervi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 17:57:33