Помогите сделать групповой чат. В своем проекте использую Django Channels. При попытке добавить сообщение ничего не выводится и в логах также не пишет никакой ошибки. Как исправить ситуацию?!
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),
]
consumers.py:
# 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)
template:
{% 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 %}