I'm trying to send chat data to my browser. The websocket is sending data to the message owner's browser. But the problem is the message is not updating from other user's browser.
class ChatConsumer(WebsocketConsumer):
def connect(self):
if(not self.scope['user'] is User):
my_id = self.scope['user']
self.me = User.objects.get(id=my_id)
else:
self.me = self.scope['user']
others_id = self.scope['url_route']['kwargs']['user_id']
other_user = User.objects.get(id=others_id)
self.thread_obj = Thread.objects.get_or_create_personal_thread(
self.me, other_user)
self.room_name = f'presonal_thread_{self.thread_obj.id}'
self.channel_layer.group_add(
self.room_name,
self.channel_name)
self.accept()
print(f'[{self.channel_name}] - {self.me.username} You are connected')
def fetch_messages(self, data):
messages = Message.objects.filter(thread=self.thread_obj)
content = {
'command': 'messages',
'messages': self.messages_to_json(messages)
}
self.send_message(content)
def new_message(self, data):
message = Message.objects.create(sender=self.me,
thread=self.thread_obj,
message=data['message'])
content = {
'command': 'new_message',
'message': self.message_to_json(message)
}
return self.chat_message(content)
def messages_to_json(self, messages):
result = []
for message in messages:
result.append(self.message_to_json(message))
return result
def message_to_json(self, message):
return {
'id': message.id,
'sender_id': message.sender.id,
'sender': message.sender.username,
'content': message.message,
'timestamp': str(message.posted_on)
}
commands = {
'fetch_messages': fetch_messages,
'new_message': new_message
}
def disconnect(self, close_code):
self.channel_layer.group_discard(
self.room_name,
self.channel_name
)
def receive(self, text_data):
data = json.loads(text_data)
self.commands[data['command']](self, data)
def chat_message(self, message):
print(message)
async_to_sync(self.channel_layer.group_send)(
self.room_name,
{
'type': 'chat_message',
'message': message
}
)
self.send(text_data=json.dumps(message))
def send_message(self, message):
self.send(text_data=json.dumps(message))
When I send chat message to the channel socket from my browser It updates only to my browser. But not updating other user's browser with the new message.
N.B: I'm new to django channel.
You can move “Sending to the group” to the receive method. The message that you send from the frontend should go directly into receive method.
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)