Very new to Django and channels. I tried to create a channel system for users to chat with other users, one-on-one. What should I do? I’m also not sure if this is a Javascript thing or the consumers.py issue.
`{{ profile.user.username|json_script:”json-sendername” }}
{{ receiver_profile.user.username|json_script:”json-receivername” }}
const senderName = JSON.parse(document.getElementById(‘json-sendername’).textContent);
const receiverName = JSON.parse(document.getElementById(‘json-receivername’).textContent);
const chatSocket = new WebSocket(
‘ws://’ + window.location.host + ‘/ws/chat/’ + senderName + ‘/’ + receiverName + ‘/’
);
chatSocket.onmessage = function(e) {
console.log(‘onmessage’)
const data = JSON.parse(e.data);
if (data.message) {
let html;
if (data.sender == senderName) {
html =
`
${data.message}
${new Date().toLocaleTimeString()}
`;
} else {
html =
`
${data.message}
${data.timestamp}
`;
}
document.querySelector(‘#chat-messages’).innerHTML += html;
} else {
alert(‘The message was empty!’);
}
}
chatSocket.onclose = function(e) {
console.log(‘onclose’)
}
document.querySelector(“#chat-message-submit”).onclick = function(e) {
const messageInput = document.querySelector(“#chat-message-input”);
const message = messageInput.value;
chatSocket.send(JSON.stringify({
‘message’: message,
‘senderName’: senderName,
‘receiverName’: receiverName
}))
messageInput.value = ”;
}
`
`class ChatConsumer(AsyncWebsocketConsumer):
@database_sync_to_async
def create_chat(self, content, sender, recipient):
return Message.objects.create(senderUsername=sender, content=content, recipientUsername=recipient)
async def connect(self):
self.sender_username = self.scope['url_route']['kwargs']['profile_username']
self.receiver_username = self.scope['url_route']['kwargs']['receiver_profile_username']
self.room_group_name = f'chat_{self.sender_username}_{self.receiver_username}'
await self.channel_layer.group_add(self.room_group_name, self.channel_name)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(self.room_group_name, self.channel_name)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
sender = self.sender_username
recipient = self.receiver_username
await self.channel_layer.group_send(self.room_group_name, {
'type': 'chat_message',
'message': message,
'sender': sender,
'recipient': recipient
})
async def chat_message(self, event):
message = event['message']
sender = event['sender']
recipient = event['recipient']
await self.create_chat(message, sender, recipient)
await self.send(text_data=json.dumps({
'message': message,
'sender': sender,
'recipient': recipient
}))`
Thanks for your help in advance 🙂
The messages are being sent through but the only thing is that the messages don’t get sent immediately, the other user has to refresh to see the most recent messages.
Timothy Ng is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.