Issue with django channels `ValueError: Invalid IPv6 URL`

Hello,
I’ve setup django channels in my project and other things like APIs and Other admin urls are working fine, but when I try to create a socket connection in my project I’m getting error

WebSocket HANDSHAKING /ws/notification/ [127.0.0.1:48494]
Exception inside application: Invalid IPv6 URL
Traceback (most recent call last):
  File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__
    return await self.application(scope, receive, send)
  File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/routing.py", line 62, in __call__
    return await application(scope, receive, send)
  File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 35, in __call__
    if self.valid_origin(parsed_origin):
  File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 54, in valid_origin
    return self.validate_origin(parsed_origin)
  File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 73, in validate_origin
    return any(
  File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 74, in <genexpr>
    pattern == "*" or self.match_allowed_origin(parsed_origin, pattern)
  File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 102, in match_allowed_origin
    pattern_hostname = urlparse("//" + pattern).hostname or pattern
  File "/usr/lib/python3.10/urllib/parse.py", line 400, in urlparse
    splitresult = urlsplit(url, scheme, allow_fragments)
  File "/usr/lib/python3.10/urllib/parse.py", line 495, in urlsplit
    raise ValueError("Invalid IPv6 URL")
ValueError: Invalid IPv6 URL
WebSocket DISCONNECT /ws/notification/ [127.0.0.1:48494]

Here are my routing.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r"ws/notification/$", consumers.NotificationConsumer.as_asgi()),
]

Here are my consumers.py

import json

from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async

class NotificationConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        print("Notification Socket Connected")
        await self.accept()

    async def disconnect(self, close_code):
        print("Notification Socket Disconnected")

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        print("text_data_json", text_data_json)
        subject_name = "Just a Test"
        if subject_name:
            msg = f"{subject_name} has been created"
            await self.send(text_data=json.dumps({"message": msg}))

Here are my templates script

    <script>
        const notificationSocket = new WebSocket(
            'ws://'
            + window.location.host
            + '/ws/notification/'
        );

        notificationSocket.onmessage = function(e) {
            const data = JSON.parse(e.data);
            console.log("-------notificationSocket.onmessage---------", data)
        };

        notificationSocket.onclose = function(e) {
            console.error('Notification Socket closed unexpectedly');
        };

        let click_test = document.getElementById("click-test");
        click_test.addEventListener("click", () => {
            console.log("click-test button clciked")
            let json = {
                id: 1,
                name: "test"
            }
            notificationSocket.send(JSON.stringify(json));
        })
        
    </script>

Can anyone help me with this one.

I can’t tell for sure from that message whether you’re getting 127.0.0.1:48494 as the url or [127.0.0.1:48494].

What does your protocol router configuration look like? That appears to be where the error is being thrown - I don’t think you’ve gotten as far as your consumer yet.

Protocol router configuration, here it is

asgi.py

import os

from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator

from v1.controller.routing import websocket_urlpatterns

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django_asgi_app = get_asgi_application()

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

What is your ALLOWED_HOSTS setting?

This is ALLOWED_HOSTS setting

settings.py 

ALLOWED_HOSTS = list(config('ALLOWED_HOSTS'))
.env

ALLOWED_HOSTS=['*']

Check to see what is actually being configured for ALLOWED_HOSTS.
Superficially, and based on the error message, it seems to me that you might be getting [['*']] as the value. Either that or ["['*']"]

I’d try setting that directly in your settings file, or printing that setting to see how it’s configured. (Or, you could check it in your shell interactively)

Yes I’ve got the pretty much idea when you asked this

I’ve got it working by checking and fixing it.

Thanks :grinning: