i'm using django and daphne and websocket to make a chat room by following a tutorial on youtube..everything worked fine , but when i send the message it does'nt show the message in the screen....it does not show any errors in the server side ..but shows 2 warniings and one error in the browser console
im intermediate in django but completely new to web sockets
Here's my script tag:
{% endblock %} {% block scripts %} {{ room.slug|json_script:"json-roomname" }}
{{ request.user.username|json_script:"json-username"}}
<script>
const roomName = JSON.parse(
document.getElementById("json-roomname").textContent
);
const usrName = JSON.parse(
document.getElementById("json-username").textContent
);
const chatSocket = new WebSocket(
"ws://" + window.location.host + "/ws/" + roomName + "/"
);
chatSocket.onmessage = function (e) {
console.log("onemssage");
const data = JSON.parse(e.data);
if (data.message) {
let html = '<div class="p-4 bg-gray-200 rounded-xl">';
html += '<p class="font-semibold">' + data.username + "</p>";
html += "<p>" + data.message + "</p></div>";
document.querySelector("#chat-messages").innerHTML += html;
} else {
alert("The message was empty!");
}
};
chatSocket.onclose = function (e) {
console.log("onclose", e);
};
document
.querySelector("#chat-message-submit")
.addEventListener("click", function (e) {
e.preventDefault();
const messageInputDom = document.querySelector("#chat-message-input");
const message = messageInputDom.value;
chatSocket.send(
JSON.stringify({
message: message,
username: usrName,
room: roomName,
})
);
messageInputDom.value = "";
return false;
});
</script>
here's my python file:
import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import sync_to_async
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
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 recieve(self,text_data):
data = json.loads(text_data)
message = data['message']
username = data['username']
room = data['room']
await self.channel_layer.group_send(
self.room_group_name,
{
'type':'chat_message',
'message': message,
'username':username,
'room':room,
}
)
async def chat_message(self,event):
message = event['message']
username = event['username']
room = event['room']
await self.send(text_data=json.dumps({
'message': message,
'username':username,
'room':room,
}))
here's routing.py:
from django.urls import path
from . import consumers
websocket_urlpatterns =[
path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()),
]
I want the message to be sent, when hitting the send button