Answer the question
In order to leave comments, you need to log in
Group Chat in Django?
Help make a group chat. I use Django Channels in my project. When you try to add a message, nothing is displayed and no error is written in the logs either. How to fix the situation?!
routing.py :
channel_routing = [
route('websocket.connect', ws_connect, path=r'^account/dashboard/projects/(?P<project_code>[0-9a-f-]+)/chat/$'),
route("websocket.receive", ws_receive),
route("websocket.disconnect", ws_disconnect),
]
# Connected to websocket.connect
@channel_session
def ws_connect(message):
query = parse.parse_qs(message['query_string'])
if 'username' not in query:
return
room = message.content['path'].strip("/")
Group('chat-%s' % room).add(message.reply_channel)
message.channel_session['room'] = room
message.channel_session['username'] = query['username'][0]
message.reply_channel.send({"accept": True})
# Connected to websocket.receive
@channel_session
def ws_receive(message):
if 'username' not in message.channel_session:
return
Group('chat-%s' % message.channel_session['room']).send({
'text': json.dumps({
'message': message.content['text'],
'username': message.channel_session['username']
})
})
# Connected to websocket.disconnect
@channel_session
def ws_disconnect(message):
Group("chat-%s" % message.channel_session['room']).discard(message.reply_channel)
{% block content %}
<h1>{{ room.code }}</h1>
<div id="msgArea"></div>
<div>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</div>
<button id="btnSubmit">Submit</button>
{% endblock content %}
{% block script %}
<script>
$(document).ready(function(){
var msgArea = $('#msgArea')
var elementMessage = $('#message')
var webSocket = new WebSocket('ws://' + window.location.host + '/account/dashboard/projects/(?P<{{ room.project_id }}>[0-9a-f-]+)/chat/');
webSocket.onmessage = function(message) {
var data = JSON.parse(message.data)
msgArea.append('<p><strong>'+ data.username + '</strong>: ' + data.message + '</p>')
}
$('#btnSubmit').click(function(e) {
webSocket.send(elementMessage.val())
})
})
</script>
{% endblock script %}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question