Чат-платформа на основе django
Я создал платформу для общения в реальном времени на фреймворке Django с использованием каналов, но я не понимаю, почему она не сохраняет историю чата в базу данных. Поэтому я добавил несколько строк кода, но теперь он показывает undefined. Может ли кто-нибудь показать мне, как исправить код в моем consumers.py?
from django.contrib.auth import get_user_model
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
from .models import Message
import json
User = get_user_model
class ChatConsumer(WebsocketConsumer):
def fetch_messages(self, data):
messages = Message.last_10_messages()
content = {
'messages': self.messages_to_json(messages)
}
self.send_messages(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 {
'author': message.author.username,
'content': message.content,
'timestamp': str(message.timestamp)
}
commands = {
'fetch_messages': fetch_messages,
'new_message': new_message
}
def connect(self):
self.room = self.scope['url_route']['kwargs']['room']
self.room_group_name = 'chat_%s' % self.room
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
)
# Receive message from WebSocket
def receive(self, 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_messages(self, message):
self.send(text_data=json.dumps(message))
def chat_message(self, event):
message = event['message']
self.send(text_data=json.dumps(message))
Вот мой пример кода view.py
def room(request, pk):
room = Room.objects.get(id=pk)
context = {
'room_name_json': mark_safe(json.dumps(pk)),
'username': mark_safe(json.dumps(request.user.username))
}
return render(request, 'base/room.html', context)
Это мой код Message sampe в models.py
class Message(models.Model):
author = models.ForeignKey(User, related_name='author_messages', on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.author.username
def last_10_messages():
return Message.objects.order_by('-timestamp').all()[:10]
Ниже приведен мой код rome.html
{% extends 'main.html' %}
{% load static %}
{% block content %}
<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">
<script src="{% static 'js/reconnecting-websocket.js' %}"></script>
<script>
// const room = JSON.parse(document.getElementById('pk').textContent);
var roomName = {{ room_name_json }};
var username = {{ username }};
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/base/'
+ 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': 'fetch_messages'
}));
messageInputDom.value = '';
};
</script>
{% endblock content %}