I’m using Django(3.2.11) with the Postgres database. I’m creating a chat app with Django channels. so I created a message consumer and save it into the database. and also created a message history consumer by room. now I want to create a user list consumer which has dynamic messages with the user name. for that I made a consumer who returns infinite data.
like:-
class ChatListConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.room_group_name = 'chat_list_%s' % self.scope['user'].user_id
self.connection = True
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
self.connection = False
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
def get_serializer(self, obj):
return {'data': ProductQueryUsersSerializer(
instance=obj.order_by('-updated_at'), many=True
).data, 'type': "chat_list"}
async def receive(self, text_data):
while self.connection:
try:
self.query = await database_sync_to_async(
ProductQueryUsers.objects.filter
)(Q(seller__user=self.scope['user']) | Q(user=self.scope['user'])
)
data = await database_sync_to_async(self.get_serializer)(self.query)
except EmptyPage:
data = {'data': [], 'type': "chat_list"}
await self.send(text_data=json.dumps(data))
and call this in javascript like:-
<div id="message"></div>
<script>
const chatSocket = new WebSocket('ws://192.168.29.72:8000/ws/chat-list/?user=VXNlcjo4Mg==');
chatSocket.onopen = function(e){
chatSocket.send(JSON.stringify({}));
console.log("open", e);
};
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
console.log(data)
data.data.forEach(function (item, index, arr) {
var element = document.getElementById(item.room_id);
if (typeof(element) != 'undefined' && element != null){
document.getElementById(item.room_id).innerHTML = item.last_message.message
} else {
document.getElementById('message').innerHTML += `<h1 id="${item.room_id}">${item.last_message.message}</h1>`
}
});
};
chatSocket.onerror = function(e){
console.log("error", e)
};
chatSocket.onclose = function(e){
console.log("close", e)
};
</script>
it infinite time return users’ list with their last message. but when it run another socket does not connect. so how can I create a user list consumer with the last message received? and call the three sockets on the same page.