Reputation: 83
I'm using django-channels
to provide a chat app on websockets. I store messages in a database. I would like to be able to send new messages to the client as soon as they get written to the database. How can I do that? I guess I need to make a WebSocketConstructor
that will recieve a post_save
signal, but I don't know exactly how to send signals to django-channels
consumers.
Upvotes: 2
Views: 1743
Reputation: 30
You should use the channel layer here like it's told in the Channels docs.
So in your post_save
signal, you can send messages from the database to the channel layer (but the question of matching the message with a channel/group is open - I think some of this information should be saved in your database).
Upvotes: 0
Reputation: 139
You can call this inside your WebSocket consumer
from channels.db import database_sync_to_async
@database_sync_to_async
def create_message(self, content):
new_message = global_message.objects.create(
sender=self.scope['user'],
content=content)
new_message.save()
return new_message
You can read more about it here: Django channels docs: Database Access. Or you can look at my source code here: ahmedyasserays/onlinechat
Upvotes: 1