How to Access URL Params in Django Channels Consumers

Question:

If i had the following url in routing.py:

/rooms/<int:id>/

How would I access the id parameter from withing a JSONWebsocketConsumer?

Asked By: svoruganti

||

Answers:

this.scope['url_path']['kwargs']['id']
Answered By: svoruganti

I think the documentation needs updating, ‘url_path’ didn’t work for me, but ‘url_route’ did.

self.scope['url_route']['kwargs']['id']
Answered By: devdrc

To access any query param you can use;

for example socket URL = ws://localhost:8000/notifications?id=11

from urllib.parse import parse_qsl
    
query_params = dict(parse_qsl(self.scope['query_string'].decode('utf-8')))
print(query_params['id'])
Answered By: Vijay Pathak

Get ID from the query param using;

self.scope['path'].split('/')[-2]
Answered By: Vijay Pathak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.