How do I preload messages on django channels?

281 views
Skip to first unread message

georgi...@gmail.com

unread,
Jun 20, 2020, 6:52:07 PM6/20/20
to Django users
I am making a django live chat app using django channels. I have a Message model where I store all the previous messages. Now I need to load them when an user connects to the websocket. This is my code:

Can you suggest me how to approach this? I got a recommendation to do it with ajax but I am not really familiar with it.

GBELE CEDRIC EMMANUEL

unread,
Jun 20, 2020, 7:55:25 PM6/20/20
to Django users
hi , i checked your code , so if you want to call all message when a users is connected , you have to create a function to call all messages when websocket is connected ,
Saisissez lfrom datetime import datetimee code ici...e code ici...

 function:

Saisissez le code ici.
@database_sync_to_async
def get_all_message(self):
   
return
Message.objects.all()..


put in the end of classe ChatConsumer according to your code after def chat_message. if is ok, go to add the following code after self.accept(): change self.accept() to await self.accept()
Saisissez le code

mess = await self.get_all_message()
for m in mess:
data = {
'author':m.user.username,
'message':m.message,

}
await self.send(text_data=json.dumps(data))
ici...
if you still have concerns i am available to help you further email : cedric...@uvci.edu.ci contact : 00225 77 53 08 22
Reply all
Reply to author
Forward
0 new messages