Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

275
Views
consumidor de lista de usuarios dinámicos en canales Django

Estoy usando Django (3.2.11) con la base de datos de Postgres. Estoy creando una aplicación de chat con canales de Django. así que creé un consumidor de mensajes y lo guardé en la base de datos. y también creó un consumidor de historial de mensajes por habitación. ahora quiero crear un consumidor de lista de usuarios que tenga mensajes dinámicos con el nombre de usuario. para eso hice un consumidor que devuelve datos infinitos. me gusta:-

 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))

y llame a esto en javascript como: -

 <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>

Es tiempo infinito devuelve la lista de usuarios con su último mensaje. pero cuando se ejecuta otro socket no se conecta. Entonces, ¿cómo puedo crear una lista de usuarios consumidor con el último mensaje recibido? y llame a los tres enchufes en la misma página.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!