Обмен сообщениями в реальном времени в django с помощью каналов
Я пытаюсь создать функциональность группового чата, но мое соединение с вебскокетом устанавливается, но сообщения отправляются, но не принимаются. Я прикрепил свой код ниже, пожалуйста, просмотрите и сообщите мне решение, я буду очень благодарен
consumers.py
from channels.generic.websocket import WebsocketConsumer
import json
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.group_id = self.scope['url_route']['kwargs']['group_id']
self.group_name = f'chat_{self.group_id}'
# Join group
self.accept()
self.channel_layer.group_add(
self.group_name,
self.channel_name
)
def disconnect(self, close_code):
# Leave room group
self.channel_layer.group_discard(
self.group_name,
self.channel_name
)
def receive(self, text_data):
try:
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
self.channel_layer.group_send(
self.group_name,
{
'type': 'chat_message',
'message': message,
}
)
except json.JSONDecodeError:
self.send(text_data=json.dumps({
'error': 'Invalid JSON format.'
}))
except Exception as e:
self.send(text_data=json.dumps({
'error': str(e)
}))
# Receive message from room group
def chat_message(self, event):
message = event['message']
# Send message to WebSocket
self.send(text_data=json.dumps({
'message': message
}))
routing.py
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path('ws/(?P<group_id>\w+)/', consumers.ChatConsumer.as_asgi()),
]
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter(
websocket_urlpatterns
)
),
})
asgi.py
import os
import django
from django.conf import settings
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.core.asgi import get_asgi_application
from all_pages.routing import websocket_urlpatterns as all_pages_ws_urls
from groupchat.routing import websocket_urlpatterns as groupchat_ws_urls
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nailSent_project.settings')
django.setup()
application = ProtocolTypeRouter({
"http": get_asgi_application(),
"websocket": AuthMiddlewareStack(
URLRouter(
all_pages_ws_urls + groupchat_ws_urls
)
)
})
html
модели
from django.db import models
from users.models import User
from special_events.models import Group
# Create your models here.
class Message(models.Model):
group = models.ForeignKey(Group, related_name='messages', on_delete=models.CASCADE)
sender = models.ForeignKey(User, related_name='sent_messages', on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
created_at = models.DateField(auto_now_add=True)
class Meta:
ordering = ('created_at',)
def __str__(self):
return f'{self.sender}'
class Group(models.Model):
name = models.ForeignKey(SpecialEvent, related_name='group_name', on_delete=models.CASCADE, null=True)
admins = models.ManyToManyField(User, related_name='admin_groups')
participants = models.ManyToManyField(User, related_name='participating_groups')
пожалуйста, просмотрите приведенный выше код и предоставьте мне какое-нибудь решение