I want to notify the client when my model is saved. I started by creating a django-signal on post_save.
@receiver(post_save, sender=Scooter)
async def scooter_post_update(sender, instance, created, **kwargs):
# Notify client here
Next I created the AsyncConsumer class from django-channels and provided its routing.
// routing.py
application = ProtocolTypeRouter({
# Empty for now (http->django views is added by default)
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(
[
path('scooters/', ScootersUpdateConsumer)
]
)
)
)
})
// consumers.py
class ScootersUpdateConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print("Connected!", event)
await self.send({
"type": "websocket.accept"
})
async def send_message(self):
await self.send({
"type": "websocket.send",
'text': 'Oy, mate!'
})
async def websocket_receive(self, event):
print("Receive!", event)
async def websocket_disconnect(self, event):
print("Disconnected!", event)
Now my question is how can I call send_message() from the scooter_post_update() method.