I have this signal to dispatch an event when a new message is created
from django.db.models.signals import post_save
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
from django.dispatch import receiver
from .serializers import MessageSerializer
from base.models import Message
@receiver(post_save, sender=Message)
def new_message(sender, instance, created, **kwargs):
channel_layer = get_channel_layer()
if created:
chat_group = instance.channel.chat_group
for member in chat_group.members:
async_to_sync(channel_layer.send)(
f"User-{member.user.id}",
{
"type": "chat_message_create",
"payload": MessageSerializer(instance).data,
},
)
this is the consumers.py
import json
from channels.generic.websocket import WebsocketConsumer
from api.serializers import UserSerializer
class ChatConsumer(WebsocketConsumer):
def connect(self):
user = self.scope["user"]
self.channel_name = f"User-{user.id}"
self.send(text_data=json.dumps(UserSerializer(user).data))
def disconnect(self, close_code):
pass
def chat_message_create(self, event):
print("Created")
self.send(text_data=json.dumps(event["payload"]))
When I create a new message in the admin panel the signal gets called but it does not get dispatched through the websocket, and any debug prints in ChatConsumer.chat_message_create won't even get printed.
Fixed the issue, I reworked the Consumers to use Groups instead of single channels