2

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.