Hi, I am using Django Channels and RestFramework to build a back-end which I can send real time data to a front-end, and my intention is when the database is updated, the front-end endpoint to be updated without it being refreshed, here is my Code so far:
#consumer.py
class MyConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.channel_layer.group_add('myCons',self.channel_name)
await self.accept()
boat = await self.get_boat(1)
boat_serializer = BoatSerializer(boat)
boat_data = boat_serializer.data
await self.send(json.dumps({"boat": boat_data,}))
async def boat_updated(self, event):
boat_data = event['boat']
await self.send(json.dumps({"boat": boat_data}))
@database_sync_to_async
def get_boat(self,pk):
boat = Boat.objects.get(pk=pk)
return boat
@receiver(post_save, sender=Boat)
def boat_post_save(sender, instance, **kwargs):
boat_data = BoatSerializer(instance).data
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)('myCons', {
'type': 'boat.updated',
'boat': boat_data,
})
And here is my front-end code:
#home.html (can be any front-end client)
const chatSocket = new WebSocket(
'ws://'
+ window.location.host
+ '/ws/myconsumer/'
);
chatSocket.onmessage = function(e) {
const data = JSON.parse(e.data);
const messageElement = document.getElementById('messageContainer');
messageElement.innerHTML = `
<h1>My ${data.boat.name}</h1>
<p>contact: ${data.boat.contact}</p>
<p>Type: ${data.boat.type}</p>
<p>Serial: ${data.boat.serial}</p>
`;
};
the code works as expected, However my concern is, I am implementing this with the help of django Signals, is there a way I can accomplish this without using signals. Or can anyone please point me to a right direction,
thanks.