'chat application is working on simple consumers.py and room.html but not working in customized consumers.py and room.html
I am developing a chat app using vscode. The problem is, when i am running the application it is opening in browser but not sending or receiving messages and also it doesn't show any error message. I am new here and so not understanding what I will do now?
The fact is, when I am using simple chat template and simple consumers.py, it is working fine but not working when I am using a customized chat template and customized consumers.py. Yet click is not taking any effect on send message but is is sending and receiving messages on shel(i.e; channel is working fine). I think the problem is in customized consumers.py and romm.html.
Any help will be accepted coordially...
Here is the not working consumers.py
from django.contrib.auth import get_user_model
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
import json
from .models import Message
User = get_user_model()
class ChatConsumer(WebsocketConsumer):
def fetch_messages(self, data):
messages = Message.last_10_messages()
content = { # 'command': 'messages',
'messages': self.messages_to_json(messages)
}
self.send_message(content)
def new_message(self, data):
author = data['from']
author_user = User.objects.filter(username=author)[0]
message = Message.objects.create(
author=author_user,
content=data['message'])
content = {
'command': 'new_message',
'message': self.message_to_json(message)
}
return self.send_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,
'author': message.contact.user.username,
'content': message.content,
'timestamp': str(message.timestamp),
}
commands = {
'fetch_messages': fetch_messages,
'new_message': new_message
}
def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
def receive(self, text_data):
# text_data_json = json.loads(text_data)
data = json.loads(text_data)
self.commands[data['command']](self, data)
def send_chat_message(self, message):
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
def send_message(self, message):
self.send(text_data=json.dumps(message))
def chat_message(self, event):
message = event['message']
self.send(text_data=json.dumps(message))
Here is not working room.html
{% load static %}
<!DOCTYPE html>
<html>
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700,300' rel='stylesheet' type='text/css'>
<script>try{Typekit.load({ async: true });}catch(e){}</script>
<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css'><link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.2/css/font-awesome.min.css'>
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" />
</head>
<body>
<div id="frame">
<div id="sidepanel">
<div id="profile">
<div class="wrap">
<img id="profile-img" src="http://emilcarlsson.se/assets/mikeross.png" class="online" alt="" />
<p>Mike Ross</p>
<i class="fa fa-chevron-down expand-button" aria-hidden="true"></i>
<div id="status-options">
<ul>
<li id="status-online" class="active"><span class="status-circle"></span> <p>Online</p></li>
<li id="status-away"><span class="status-circle"></span> <p>Away</p></li>
<li id="status-busy"><span class="status-circle"></span> <p>Busy</p></li>
<li id="status-offline"><span class="status-circle"></span> <p>Offline</p></li>
</ul>
</div>
<div id="expanded">
<label for="twitter"><i class="fa fa-facebook fa-fw" aria-hidden="true"></i></label>
<input name="twitter" type="text" value="mikeross" />
<label for="twitter"><i class="fa fa-twitter fa-fw" aria-hidden="true"></i></label>
<input name="twitter" type="text" value="ross81" />
<label for="twitter"><i class="fa fa-instagram fa-fw" aria-hidden="true"></i></label>
<input name="twitter" type="text" value="mike.ross" />
</div>
</div>
</div>
<div id="search">
<label for=""><i class="fa fa-search" aria-hidden="true"></i></label>
<input type="text" placeholder="Search contacts..." />
</div>
<div id="contacts">
<ul>
<li class="contact">
<div class="wrap">
<span class="contact-status online"></span>
<img src="http://emilcarlsson.se/assets/louislitt.png" alt="" />
<div class="meta">
<p class="name">Louis Litt</p>
<p class="preview">You just got LITT up, Mike.</p>
</div>
</div>
</li>
<li class="contact active">
<div class="wrap">
<span class="contact-status busy"></span>
<img src="http://emilcarlsson.se/assets/harveyspecter.png" alt="" />
<div class="meta">
<p class="name">{{ username }}</p>
<!-- <p class="preview">Wrong. You take the gun, or you pull out a bigger one. Or, you call their bluff. Or, you do any one of a hundred and forty six other things.</p> -->
</div>
</div>
</li>
</ul>
</div>
<div id="bottom-bar">
<button id="addcontact"><i class="fa fa-user-plus fa-fw" aria-hidden="true"></i> <span>Add contact</span></button>
<button id="settings"><i class="fa fa-cog fa-fw" aria-hidden="true"></i> <span>Settings</span></button>
</div>
</div>
<div class="content">
<div class="contact-profile">
<img src="http://emilcarlsson.se/assets/harveyspecter.png" alt="" />
<p>{{ username }}</p>
<div class="social-media">
<i class="fa fa-facebook" aria-hidden="true"></i>
<i class="fa fa-twitter" aria-hidden="true"></i>
<i class="fa fa-instagram" aria-hidden="true"></i>
</div>
</div>
<div class="messages">
<ul id="chat-log">
<!-- <li class="sent">
<img src="http://emilcarlsson.se/assets/mikeross.png" alt="" />
<p>How the hell am I supposed to get a jury to believe you when I am not even sure that I do?!</p>
</li>
<li class="replies">
<img src="http://emilcarlsson.se/assets/harveyspecter.png" alt="" />
<p>When you're backed against the wall, break the god damn thing down.</p>
</li> -->
</ul>
</div>
<div class="message-input">
<div class="wrap">
<input id="chat-message-input" type="text" placeholder="Write your message..." />
<i class="fa fa-paperclip attachment" aria-hidden="true"></i>
<button id="chat-message-submit" class="submit">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</button>
</div>
</div>
</div>
</div>
<!-- {{ room_name|json_script:"room-name" }} -->
<script src="{% static 'main.js' %}"></script>
<script src="{% static 'reconnecting-websocket.js' %}"></script>
<script>
var roomName = {{ room_name_json }};
var username = {{ username }};
const chatSocket = new ReconnectingWebSocket(
'ws://' + window.location.host +
'/ws/chat/' + roomName + '/');
chatSocket.onopen = function(e){
fetchMessages();
}
chatSocket.onmessage = function(e){
var data = JSON.parse(e.data);
if(data['command'] === 'messages'){
for(let i=0; i<data['messages'].length; i++){
createMessage(data['messages'][i]);
}
} else if(data['command'] === 'new_message'){
createMessage(data['message']);
}
};
chatSocket.onclose = function(e){
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').onkeyup = function(e){
if (e.keyCode === 13){ // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e){
var messageInputDom = document.getElementById('chat-message-input');
var message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'command': 'new_message',
'message': message,
'from': username,
}));
messageInputDom.value = '';
};
function fetchMessages(){
chatSocket.send(JSON.stringify({'command': 'fetch_messages'}));
}
function createMessage(data){
var author = data['author'];
var msgListTag = document.createElement('li');
var imgTag = document.createElement('img');
var pTag = document.createElement('p');
pTag.textContent = data.content;
imgTag.src = 'https://thumbs.dreamstime.com/z/man-cartoon-face-glasses-man-cartoon-face-glasses-vector-illustration-120285200.jpg';
if(author === username){
msgListTag.className = 'sent';
}else{
msgListTag.className = 'replies';
}
msgListTag.appendChild(imgTag);
msgListTag.appendChild(pTag);
document.querySelector('#chat-log').appendChild(msgListTag);
}
</script>
</body></html>
Here is the working files consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
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
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
# Receive message from room group
async def chat_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
}))
Here is working room.html files
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Chat Room</title>
</head>
<body>
<script src="{% static 'reconnecting-websocket.js'%}"></script>
<textarea id="chat-log" cols="100" rows="20"></textarea><br>
<input id="chat-message-input" type="text" size="100"><br>
<input id="chat-message-submit" type="button" value="Send">
{{ room_name|json_script:"room-name" }}
<script>
const roomName = JSON.parse(document.getElementById('room-name').textContent);
const chatSocket = new ReconnectingWebSocket(
'ws://'
+ window.location.host
+ '/ws/chat/'
+ roomName
+ '/'
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
document.querySelector('#chat-log').value += (data.message + '\n');
};
chatSocket.onclose = function(e) {
console.error('Chat socket closed unexpectedly');
};
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function(e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
document.querySelector('#chat-message-submit').onclick = function(e) {
const messageInputDom = document.querySelector('#chat-message-input');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message,
'command': 'new_message'
}));
messageInputDom.value = '';
};
</script>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
