WebSocket django channels doesn't work with postman

Django Channels Throw error with postman while working well with Html.

I'm following Django Socket Tutorial

"here's the error showing in Django".

WebSocket HANDSHAKING /ws/chat/roomName/ [127.0.0.1:56504]
WebSocket REJECT /ws/chat/roomName/ [127.0.0.1:56504]
WebSocket DISCONNECT /ws/chat/roomName/ [127.0.0.1:56504]

"Error showing in postman when connecting to ws://127.0.0.1:8000/ws/chat/roomName/"

Sec-WebSocket-Version: 13
Sec-WebSocket-Key: fSSuMD2QozIrgywqTX38/A==
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Host: 127.0.0.1:8000

My Code asgi.py

django_asgi_app = get_asgi_application()

import digital_signage.playlist_management.routing

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(digital_signage.playlist_management.routing.websocket_urlpatterns))
        ),
    }
)

consumer.py

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        print("self", self)
        self.accept()

This happens because of ALLOWED_HOST in settings. You can put * if you on development mode but it will affect the whole project. Instead you can do something like below

You can wrap asgi.py with OriginValidator (can be import from channels.security.websocket)

application = ProtocolTypeRouter(
{
    "http": django_asgi_app,
    "websocket": OriginValidator(
        AuthMiddlewareStack(
            URLRouter(Chat.routing.websocket_urlpatterns)
        ),
        ['*']
    )
    
}

)

Back to Top