# Can't connect django with javascript on non localhost ip address

**URL:** <https://forum.djangoproject.com/t/cant-connect-django-with-javascript-on-non-localhost-ip-address/28566>\
**Category:** Async/Channels\
**Created:** [February 29, 2024, 9:04pm UTC](https://forum.djangoproject.com/t/cant-connect-django-with-javascript-on-non-localhost-ip-address/28566 "2024-02-29T21:04:25Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![nikhil-kumar-tomar](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhil-kumar-tomar/32/19534_2.png) [@nikhil-kumar-tomar](https://forum.djangoproject.com/u/nikhil-kumar-tomar)\
**Post date:** [February 29, 2024, 9:04pm UTC](https://forum.djangoproject.com/t/cant-connect-django-with-javascript-on-non-localhost-ip-address/28566/1 "2024-02-29T21:04:25Z")

</div>

Hello.  
I am trying to connect javascript to django. And I am hosting my django web app on [http://0.0.0.0:8000/](http://0.0.0.0:8000/)  
What I actually want is for local network devices to connect as well there they are able to access my website using my internal ip address and port. like 10.7.5.142:8000.

The problem is I am using Websocket currently. And while the websockets are connecting on localhost:8000. But they are not connection on the above mentioned ip address.

COrs is setup. I just want to make this django project a little less secure because I only want to show the implementation I am not concerned about the security right now.

```auto
settings.py
DEBUG = True
ALLOWED_HOSTS = ['*']

# Application definition

INSTALLED_APPS = [
    "daphne",
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'chat',
    'chat_platform',
    # Third Party Apps
    'widget_tweaks',
    # 'corsheaders'
    ]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'corsheaders.middleware.CorsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True
ROOT_URLCONF = 'chat_room.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'chat_room.wsgi.application'
ASGI_APPLICATION = "chat_room.asgi.application"

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [(config("REDIS_HOST",'127.0.0.1'), config("REDIS_PORT",'6379'))],
        },
    },
}
... A lot more unimportant things

```

asgi.py

```auto
import os

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

from chat.routing import websocket_urlpatterns

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django_asgi_app = get_asgi_application()

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

```

```auto
class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
        self.room_group_name = f"{self.room_name}"
        self.current_channel_name = self.scope["url_route"]["kwargs"]["channel_name"]

        await self.channel_layer.group_add(self.room_group_name, self.channel_name)
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(self.room_group_name, self.channel_name)

    async def receive(self, text_data):
        data = json.loads(text_data)
        message = data['message']
        receiver_channel_name = data['receiver_channel_name']

        await self.channel_layer.group_send(self.room_group_name, {
            "type": "chat.message",
            "to":receiver_channel_name,
            "message":message
        })

    async def chat_message(self, event):
        message = event['message']
        if event["to"] == self.current_channel_name:
            await self.send(text_data=json.dumps({
                'message': message
            }))

```

 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/3X/b/d/bda82e19563dcb28255bbedff94cf6d677d71d1d.png)

I have faced this problem in Rest Framework as well. There I just set the AUthentication and Permission classes to empty lists. Then The javascript connections worked. But here I don’t have a clear Idea of what to do.  
Again I do not care much about security at the current moment and would like to use this freeely.  
Thanks for any help in advance.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 29, 2024, 9:10pm UTC](https://forum.djangoproject.com/t/cant-connect-django-with-javascript-on-non-localhost-ip-address/28566/2 "2024-02-29T21:10:32Z")

</div>

Please post your `websocket_urlpatterns` and the command line you’re using to run Daphne.

Also, your definition for the CHANNEL\_LAYER is incorrect. See the docs at [Channel Layers — Channels 4.0.0 documentation](https://channels.readthedocs.io/en/latest/topics/channel_layers.html#redis-channel-layer)

---

<div class="post-metadata">

**Author:** ![nikhil-kumar-tomar](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhil-kumar-tomar/32/19534_2.png) [@nikhil-kumar-tomar](https://forum.djangoproject.com/u/nikhil-kumar-tomar)\
**Post date:** [February 29, 2024, 9:34pm UTC](https://forum.djangoproject.com/t/cant-connect-django-with-javascript-on-non-localhost-ip-address/28566/3 "2024-02-29T21:34:36Z")

</div>

websocket\_urlpatterns = [  
re\_path(r"ws/chat/(?P\<room\_name\>\w+)/(?P\<channel\_name\>\w+)/$", consumers.ChatConsumer.as\_asgi()),  
]

I am using python .\manage.py runserver 0.0.0.0:8000.  
I am not using a specific command to run daphne, It is being taken care of from above only.

One more thing I want to add.  
I saw that

```auto
await self.channel_layer.group_add(self.room_group_name, self.channel_name)

```

When I comment above line, the connection is established though I cannot sent messages. Meaning group creation is actually causing the problems.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 29, 2024, 10:40pm UTC](https://forum.djangoproject.com/t/cant-connect-django-with-javascript-on-non-localhost-ip-address/28566/4 "2024-02-29T22:40:17Z")

</div>

Did you fix the CHANNEL\_LAYERS definition as I pointed out above?

---

<div class="post-metadata">

**Author:** ![nikhil-kumar-tomar](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhil-kumar-tomar/32/19534_2.png) [@nikhil-kumar-tomar](https://forum.djangoproject.com/u/nikhil-kumar-tomar)\
**Post date:** [March 1, 2024, 4:35am UTC](https://forum.djangoproject.com/t/cant-connect-django-with-javascript-on-non-localhost-ip-address/28566/5 "2024-03-01T04:35:11Z")

</div>

I found the solution, actually the connection to me Redis was failing due to which groups were not made and ultimately websockets were denied.everything is working fine now
