[Django]-Send notification on post_save signal in django

1👍

You can simply add a signal for a post_save

@receiver(post_save, sender=Deposit)
def signal_deposit_save(sender, instance, created, **kwargs):
    if created: # This means it is a new row
        # Send notification using django-channels

8👍

You can use the save method of your Django model, like so:

from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer

class Info(models.Model):
    # your model fields

    def save(self, force_insert=False, force_update=False, using=None,
             update_fields=None):
        super(Info, self).save(force_insert, force_update, using, update_fields)
        # send info to channel
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            'infochannel',
            {
                'type': 'infochannel.message',
                'device_id': str(self.device_id)
            }
        )

And in the consumer:

from channels.generic.websocket import AsyncWebsocketConsumer

class DataConsumer(AsyncWebsocketConsumer):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.group_name = ''

    async def connect(self):
        # we are using one fixed group
        self.group_name = 'infochannel'

        await self.channel_layer.group_add(
            self.group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard('infochannel', self.channel_name)

    async def infochannel_message(self, event):
        # Send message to websocket group
        await self.send(text_data=event['device_id'])

Where device_id is a field on my model, and of course you also have to set up routing, redis_channels, and so on.

👤normic

Leave a comment