Django Channels: WebsocketCommunicator.connect() returns (False, None) and websockets clients get 'server rejected WebSocket connection: HTTP 403': AllowedHostsOriginValidator needs an Origin header
Fix: send an Origin whose host is in ALLOWED_HOSTS. In tests: WebsocketCommunicator(application, '/ws/project/1/', headers=[(b'origin', b'http://localhost')]). From a script: websockets.connect(url, additional_headers={'Origin': 'http://localhost:8000'}). Alternatively test the consumer directly (MyConsumer.as_asgi()) instead of the full asgi.py application.
Cause: the standard asgi.py wraps the websocket router in AllowedHostsOriginValidator(AuthMiddlewareStack(URLRouter(...))). Browsers always send Origin, but WebsocketCommunicator and command-line clients don't, and channels' OriginValidator returns False for a missing Origin unless '*' is in ALLOWED_HOSTS. The handshake is denied, which shows up as connected == False in tests and HTTP 403 for real clients.
It is easy to blame pytest-asyncio event loops, CHANNEL_LAYERS or the test database for the failing connect; overriding those didn't help. Verified with channels 4.2.0, Django 5.1.3, pytest-asyncio 0.24.0: without the header connect() gives (False, None); with (b'origin', b'http://localhost') and ALLOWED_HOSTS=['localhost'] it gives (True, None).
Second gotcha in the same test: mark it @pytest.mark.django_db(transaction=True), otherwise the consumer fails with 'RuntimeError: Database access not allowed, use the "django_db" mark...' when channels closes old DB connections.