Is it Possible to do a private chat with Django Channels

Viewed 2632

I want to do a one to one private chat with Django-channels, but i cant find any article/post about it, all i see is on creating group chat.

It seem to me like Django-channel can only be used in creating group chat and group gaming system. I want to know if django-channels can handle a one to one private chat and how do i go about that.

Thanks in advance.

2 Answers

I'm not familair with django-channel but reading through the tutorial it seems to me that you can manage channels and their privacy using models and permissions.

class OneOnOneRoom(models.Model):
    user1 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name = 'user1')
    user2 = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name = 'user2')
    room_name = models.CharField(max_length = 128, unique=True)
    

Then for your view (this is a modification of the example in the documentation

def room(request, room_name):
    if not OneOnOneRoom.objects.filter(room_name=room_name).exists():
        OneOnOneRoom.objects.create(...)#create the room with the users information forwarded with your request 
    room = OneOnOneRoom.objects.get(room_name=room_name)
    if request.User != room.user1 and request.User != room.user2:
            return HttpResponseBadRequest() #or deny permission some other way
    return render(request, 'chat/room.html', {
        
        'room_name_json': mark_safe(json.dumps(room_name))
    })

When a user tries to join a channel, reject the view.

NOTE:

I'm not sure is that is the exact way you should compare users, but it should convey the idea

I, too, had a hard time finding information about this and ended up buying a course that does it like @robotHamster suggests,but I didn't find that solution elegant.

What you can do is send messages directly to other channels, instead of other groups (and let the group send to all channels in it).

More information here: https://channels.readthedocs.io/en/latest/topics/channel_layers.html#synchronous-functions

Basically, instead of using channel_layer.group_send, you'll use channel_layer.send.

Related