[Fixed]-Sending data to django channels groups via django views

9👍

credits to @Matthaus Woolard for making the concept pretty clear.

So this was the problem:

The client had disconnected when I tried to send the message from the django view. This happened as the server restarted upon code change. I refreshed the browser and it started to work.

Silly mistake

So to summarize:

Add the following in connect() in case of Synchronous consumer:

async_to_sync(self.channel_layer.group_add)('events', self.channel_name)

or add this incase of Async Consumer:

await self.channel_layer.group_add('events', self.channel_name)

create a view as follows:

def alarm(request):
   layer = get_channel_layer()
   async_to_sync(layer.group_send)('events', {
           'type': 'events.alarm',
           'content': 'triggered'
        })
   return HttpResponse('<p>Done</p>')
👤Adarsh

Leave a comment