I have django project with rooms, and i want to create real time chat for rooms with channels library, this chat works with data from url kinda example.com/room_name/person_name, but i have rooms that have static url(example below),how to adjust that for my project. I want to show request.user.username instead of person_name in url, and i want to use room_detail url instead of room_name that i should type every time
views.py
class RoomDetail(DetailView):
model = Room
template_name = 'rooms/room_detail.html'
context_object_name = 'room_detail'
slug_field = 'invite_url'
slug_url_kwarg = 'url'
consumers.py
class Consumer(WebsocketConsumer):
def connect(self):
self.room_name=self.scope['url_route']['kwargs']['room_name']
self.room_group_name='chat_%s' % self.room_name
self.person_name=self.scope['url_route']['kwargs']['person_name']
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
"type":"chat_message",
"message":self.person_name+" Joined Chat"
}
)
self.accept()
def disconnect(self, code):
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
"type":"chat_message",
"message":self.person_name+" Left Chat"
}
)
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)
def receive(self, text_data=None, bytes_data=None):
text_data_json=json.loads(text_data)
message=text_data_json['message']
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type':'chat_message',
'message':self.user+" : "+message
}
)
def chat_message(self,event):
message=event['message']
self.send(text_data=json.dumps({
'message':message
}))
urls.py
path('rooms/<url>/', RoomDetail.as_view(), name='room_detail'),
I'm not sure, I understand you will. but in case of you need to get username, you can simple use
self.scope['user'].username
instead of getting it from urls pattern.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.