Search code examples
pythondjangodjango-channels

How do I configure the sending of json objects to Django Channels?


How do I configure the sending of json objects to Django Channels? To ensure that when adding a new object in the admin panel, it immediately appeared on the front in real time. Maybe someone has any examples. Would be very grateful.

There is a Factory object:

models.py

class Factory(models.Model):

     OBJECT_CHOICES = (
            ('Завод', 'Завод'),
            ('Вышка', 'Вышка'),
            ('Хранилище', 'Хранилище'),
            ('АЗС', 'АЗС')
        )

    title = models.CharField(max_length=200)
    choice = models.CharField(max_length=15, choices=OBJECT_CHOICES, default = '')
    address = YmapCoord(max_length=200, start_query=u'Россия', size_width=500, size_height=500, unique = True)

When a GET request is made to / getFactory /, JSON type is issued

[
   {
    "title": "factory",
    "choice": "Завод",
    "address": [
        55.744607932133505,
        48.99357300960071
    ]
   }
]

Solution

  • First of all, you need a consumer and you should define groups field there.

    A WebsocketConsumer’s channel will automatically be added to (on connect) and removed from (on disconnect) any groups whose names appear in the consumer’s groups class attribute.

    Then your front-end should connect to the consumer somehow and listen for updates. Once that is done you can send new messages from any place of your project. For example, from post_save signal.

    from channels import Group
    from django.db.models import signals
    from django.dispatch import receiver
    
    
    @receiver(signals.post_save, sender=Factory)
    def notify_group(sender, instance, **kwargs):
        if kwargs['created']:
            group_name = 'your group'
            Group(group_name).send({'text': 'message or object'})