New chat message notification Django Channels

后端 未结 2 1576
时光取名叫无心
时光取名叫无心 2020-12-13 21:36

I\'ve got Django Channels 2.1.2 set up in my Django app by following a tutorial and now need to set up a notification system for new messages. I want to do this

2条回答
  •  时光取名叫无心
    2020-12-13 22:25

    I couldn't mark this as a duplicate, because there is a bounty on it. But the solution is, you need more than two models. According to this post, your models.py should look something like this:

    class MessageThread(models.Model):
        title = models.CharField()
        clients = models.ManyToManyField(User, blank=True)
    
    class Message(models.Model):
        date = models.DateField()
        text = models.CharField()
        thread = models.ForeignKey('messaging.MessageThread', on_delete=models.CASCADE)
        sender = models.ForeignKey(User, on_delete=models.SET_NULL)
    

    Your consumers.py should look like this:

    class ChatConsumer(WebSocketConsumer):
        def connect(self):
            if self.scope['user'].is_authenticated:
                self.accept()
                # add connection to existing groups
                for thread in MessageThread.objects.filter(clients=self.scope['user']).values('id'):
                    async_to_sync(self.channel_layer.group_add)(thread.id, self.channel_name)
                # store client channel name in the user session
                self.scope['session']['channel_name'] = self.channel_name
                self.scope['session'].save()
    
        def disconnect(self, close_code):
            # remove channel name from session
            if self.scope['user'].is_authenticated:
                if 'channel_name' in self.scope['session']:
                    del self.scope['session']['channel_name']
                    self.scope['session'].save()
                async_to_sync(self.channel_layer.group_discard)(self.scope['user'].id, self.channel_name)
    

提交回复
热议问题