I have a problem regarding my consumer. or Django signal? I wasn't able to send a message from my group in the web socket by using my Django signal to execute the function from my consumer.
I have here a Django signal code, which executes/tracks my model if being updated and it executes correctly:
@receiver(post_save, sender=Person)def check_got_data_update_to_true(sender, instance, **kwargs): if instance.got_data: print(f"from django signals: {instance.id}") print(f"from django signals: {instance.company_website}") message = f"from django signals: {instance.id}" send_data_to_consumers(message)def send_data_to_consumers(message): channel_layer = get_channel_layer() try: async_to_sync(channel_layer.group_send)("test", {"type": "handle_signal_message","message": message, }, ) print("Group message sent successfully.") except Exception as e: print(f"Error sending group message: {str(e)}")
now when there is an update from my model, my Django signals execute properly and output the message of Group message sent successfully in logs.
Now here, I have a consumer that my Django signals calling the function of handle_signal_message
and I don't know why this doesn't execute. Since when i put a print inside the function, it doesn't print.Here is the full code of my consumer:
from channels.generic.websocket import ( AsyncJsonWebsocketConsumer, AsyncWebsocketConsumer, JsonWebsocketConsumer,)import jsonclass TestConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.channel_layer.group_add("test", self.channel_name) await self.accept() print("Connected!") async def disconnect(self, close_code): print("Disconnected!") await self.channel_layer.group_discard("test", self.channel_name) async def receive(self, text_data): data = json.loads(text_data) print(data) await self.events_handler[data["event"]](self, data) async def handle_signal_message(self, event): message = event["message"] print(f"Received message in handle_signal_message: {message}") await self.send_json({"message_from_signal": message}) ### client events here ### async def event_received_message(self, data): msg = data["data"] print(msg) ### client end of events ### ### events handler ### events_handler = {"EVENT_MESSAGE_RECEIVE": event_received_message} ### end of events handler ###
I'm using a postman to test the connection and it works fine. Actually, my server receives messages from my Postman client connecting in the ws. My problem is that in Django signals don't execute my consumer function.